Flash Messages in Rails

2020-02-25 00:35:08 +0000

What are flash messages?

A flash message is a way to communicate information with the users of your Rails application so they can know what happens as a result of their actions.

Example messages:

“Password changed correctly” (confirmation) “User not found” (error) You set these flash messages in your controllers, then you render them in your views. Your users can then act accordingly.

Let’s learn exactly how this works!

How to Use Flash Messages

You can work with these notification messages using the flash helper method.

It behaves a lot like a Ruby hash.

The flash object has methods like keys, any? or each & you can access a particular message with [].

What types of flash messages can you set?

By default you have:

  1. notice
  2. alert

Here’s an example of how to use it:

flash.alert = "User not found." 

Or if you prefer:

flash[:alert] = "User not found." 

(Only a style difference.)

You can use this code inside your controller actions, like index, create, new, etc.

Another way is this:

redirect_to :books_path, notice: "Book not found"

This allows you to redirect & create a flash message in one step.

Nice!

Alert vs Notice

As far as I understand it doesn’t really matter if you use alert or notice.

Use the one that feels more natural for your situation.

I like to think about alert as an error message & a notice as a confirmation message.

Separating them helps you style them differently.

For example:

You can show alerts in red & notices in green.

It’s also possible to create your own flash types by using the add_flash_types controller method.

Like this:

class ApplicationController
  add_flash_types :info, :error, :warning
end 

Rendering Flash Messages

Flash messages aren’t shown automatically.

You have to render them inside one of your views so users can see them.

Consider adding this to your application layout.

Here’s a code example:

<% flash.each do |type, msg| %>
  <div>
    <%= msg %>
  </div>
<% end %>

Put this wherever you want to show your notice, usually at the top of the page, below the menu bar.

Remember:

Once you render a message it’ll be removed from flash, so it won’t be shown again.

Styling Your Notices & Alert Messages

Flash messages don’t have any built-in design or style.

Solution?

If you’re using Bootstrap, you can use the “alert alert-info” CSS class to make flash messages look good.

Example:

<% flash.each do |type, msg| %>
  <div class="alert alert-info">
    <%= msg %>
  </div>
<% end %>

It looks like this:

If you’re NOT using Bootstrap, then you can write your own CSS to make it look however you want.

When Are Flash Messages Rendered?

Flash messages are only removed on your next controller action, after your display them.

Implications:

If you redirect_to, then render a flash message, that’s good If you redirect_to & DON’T render the message, the message will stick around, in the flash hash If you render on the same action that you’re setting the flash message, that flash message will be available, but NOT removed so it will stay around & potentially be shown twice So…

What if you want to set a flash message for the current action?

That’s where flash.now comes in!

Here’s an example:

def index
  @books = Book.all

  flash.now[:notice] = "We have exactly #{@books.size} books available."
end

This will render the index view.

The notice message will be shown & removed from flash so it won’t be shown twice.

In other words:

You only need to use flash.now if you’re going to render instead of redirecting.

Summary

You’ve learned about flash messages in Rails & how to use them correctly!

Btw, flash messages aren’t the same as validation errors. Validations are associated with the model object, and you access these validation messages with the errors method, like @user.errors.

Now it’s your turn to put this into practice by writing some code.

Thanks for reading!


Install Docker on Ubuntu 18.10

2020-02-19 00:22:50 +0000

useful image

let’s install Docker

Step 1: Update Local Database Update the local database with the command:

sudo apt-get update

Step 2: Download Dependencies You’ll need to run these commands to allow your operating system to access the Docker repositories over HTTPS.

In the terminal window, type:

tinix@yandex:/$ sudo apt-get install apt-transport-https ca-certificates curl software-properties-common

To clarify, here’s a brief breakdown of each command:

  • apt-transport-https: Allows the package manager to transfer files and data over https
  • ca-certificates: Allows the system (and web browser) to check security certificates
  • curl: This is a tool for transferring data
  • software-properties-common: Adds scripts for managing software

Step 3: Add Docker’s GPG Key The GPG key is a security feature.

To ensure that the software you’re installing is authentic, enter:

tinix@yandex:/$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Add the repository

tinix@yandex:/$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

Update again

tinix@yandex:/$ sudo apt-get update

install docker

 tinix@yandex:/$ sudo apt-get install docker-ce

start with the system

tinix@yandex:/$ sudo systemctl enable docker

add new user

for example check you user

tinix@yandex:/$ whoami
tinix
$ sudo usermod -aG docker tinix

leave session

tinix@yandex:/$ exit

start again with the new user and check

tinix@yandex:/$ docker run hello-world

that’s all folks..!!


Ruby vs Elixir , Rails vs Phoenix - part 2

2018-09-28 16:52:56 +0000

useful image

Dev Tools rake vs. mix In Ruby, there is rake, in Elixir there is mix.

Mix is a build tool that provides tasks for creating, compiling, and testing Elixir projects, managing its dependencies, and more.

Like Rails, Phoenix provides various mix commands to handle common tasks. Most of these commands should feel familiar:

mix phoenix.new my_app
mix phoenix.server
mix ecto.migrate
mix phoenix.gen.html User users email:string
mix test
MIX_ENV=test mix ecto.migrate
 

# irb vs. iex Ruby gives us the Interactive Ruby Shell (IRB or irb). IEx is Elixir’s Interactive Shell.

Run it within your Elixir project using the command: iex -S mix. The -S tells iex to execute the Mixfile (mix.exs), which handles configuring the project.

Unlike irb, you will have to hit Ctrl-C twice to exit, instead of Ctrl-D.

If you are like me and prefer to have a console session open while developing, usually with some state built up, then the recompile() helper will come in handy. Calling it eliminates having to start a new iex session (and lose all your state) when you’ve made changes to a file.

Another handy, time-saving tip:

Create a .iex.exs file in your project root to alias your project’s modules so you can call, Repo.all, instead of, MyApp.Repo.all.

The first time I fired up iex and wanted to grab the first User in the database, I got hit with:

(UndefinedFunctionError) function MyApp.User.first/0 is undefined or privateefinedFunctionError) function
 

Remember, Elixir is functional, so we can’t do things like User.first.

Here is the equivalent in Phoenix (technically Ecto, the database layer):

User |> Repo.all |> List.first
 

That is a lot of typing. Adding a couple convenience functions to my project’s Repo module allows me to call Repo.first User. That is better.

defmodule MyApp.Repo do
  use Ecto.Repo, otp_app: :elformo
  alias __MODULE__

  def first(query) do
    query |> Ecto.Query.first |> Repo.one
  end

  def last(query) do
    query |> Ecto.Query.last |> Repo.one
  end
end
 

Ruby vs Elixir , Rails vs Phoenix - part 1

2018-09-28 16:52:56 +0000

useful image

This is not a, “Which is better?”, post. It is more a way to help other developers, like myself, who have a background in Rails development and are interested in Elixir and Phoenix.

Elixir != Ruby and Phoenix != Rails. Even though there may be some similarities between both, it is beneficial to stay open to innovative and often lateral approaches in Elixir/Phoenix.

If you are a Ruby/Rails developer who is interested in adding Elixir/Phoenix to your toolbelt, then I hope this post serves as a helpful starting point.

class User < Struct.new(:first, :last)
  def self.full_name(user)
    "#{user.first} #{user.last}"
  end
end

user = User.new("George", "Tinix")
User.full_name(user) 
#=> "George Tinix"
 

Notice that we pass user to the full_name method. There are no “object instances” to call methods on in Elixir.

defmodule User do
  defstruct [:first, :last]

  def full_name(user) do
    "#{user.first} #{user.last}"
  end
end

user = %User{first: "George", last: "Tinix"}
User.full_name(user)
#=> "George Tinix"
 

Embrace Pattern Matching

In Ruby, conditionals are predominant, but in Elixir it is more favorable to use pattern matching.

In Ruby, you might see something like this:

def notify_user(user)
  if user.send_emails? do
   #Send emails
  end
end
 

In Elixir, we would use pattern matching against the data structure of the user argument:

 def notify_user(%User{send_emails?: true}) do
  #Send emails
end
def notify_user(user), do: user
 

The above example shows the use of pattern matching within function definitions but we can also use pattern matching to control the flow of logic.

In Rails, this could be considered the equivalent of returning a Result object for handling outcomes beyond just true or false.

In Elixir, you would utilize pattern matching on a function’s result. The following is quite common to see in Phoenix controllers:

 case MyApp.do_something() do
  {:ok, value}     -> # do stuff ...
  {:error, errors} -> # do different stuff...
end
 

Updating a rails password via the rails console

2018-08-07 16:47:20 +0000

I forgot one of my test passwords and realized I didn’t have a quick way to redo the password. There is a simple handful of commands fix this:

irb(main):001:0> u = User.find_by_id(1)
  User Load (3.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
=> #<User id: 1, name: "JJ Asghar", email: "jjasghar@gmail.com", created_at: "2014-04-18 17:46:48", updated_at: "2014-04-25 23:21:10", password_digest: "$2a$10$or/wJw1I8Wpf0lXNbtawveoQXETGJbUkv/VwXQXzn92r...", remember_token: "uUJTExCyt4mpAOpQWd4PMA">
irb(main):002:0> u
=> #<User id: 1, name: "JJ Asghar", email: "jjasghar@gmail.com", created_at: "2014-04-18 17:46:48", updated_at: "2014-04-25 23:21:10", password_digest: "$2a$10$or/wJw1I8Wpf0lXNbtawveoQXETGJbUkv/VwXQXzn92r...", remember_token: "uUJTExCyt4mpAOpQWd4PMA">
irb(main):003:0> u.password = "a_stupid_pa$$word"
=> "_stupid_pa$$word"
irb(main):004:0> u.password_confirmation = "a_stupid_pa$$word"
=> "_stupid_pa$$word"
irb(main):005:0> u.save
   (2.0ms)  BEGIN
  User Exists (12.2ms)  SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('jjasghar@gmail.com') AND "users"."id" != 1) LIMIT 1
   (15.8ms)  UPDATE "users" SET "password_digest" = '$2a$10$Za7prnrSthhE90AvB15BNOMl8sf3oL7onBpZ45nH/9skwHfn1EFA.', "remember_token" = 'zOZYjEVovO143qrX1yhibw', "updated_at" = '2014-04-25 23:24:39.329502' WHERE "users"."id" = 1
   (4.6ms)  COMMIT
=> true
irb(main):006:0>

As you can see, you need to create an object via a find_by_, in my case id and write it to u. After that I change the password key to a_stupid_pa$$word along with the password_confirmation. I then write it to the database via u.save.




subscribe via RSS