Gemfile · I codes and I blogs

.try

This Ruby method returns nil rather than raising an exception when called on a non-existent object.

$ rails console
2.1.0 :001 > nil.admin?
NoMethodError: undefined method 'admin?' for nil:NilClass
... stack trace ...
2.1.0 :002 > nil.try(:admin)
 => nil

Here’s a practical example: Is the currently signed in user an admin? If so, he should see site admin links, otherwise they should be hidden:

any_view_file.html.erb:

<% if current_user.admin? %>
  Show links
<% end %>

The above code breaks when the page is viewed by a non-signed-in visitor and current_user is not set (i.e. is nil).

The if statement can be augmented to include two tests:

<% if current_user && current_user.admin? %>
  Show links
<% end %>

Or the try method can be used to clean up the code:

<% if current_user.try(:admin) %>
  Show links
<% end %>

The if statement will return true if the currently signed in user is an admin, false if he is not, and nil if there is no signed in user. Since nil is falsey, the admin links remain nicely hidden.

(This approach merely cleans up the layout for unauthorized users. It should not be relied on to actually prevent unauthorized access to controller actions.)

Nuking all changes with Git

After looking it up twice in one (less than productive) day…

$ git reset --hard # delete all changes from tracked files
$ git clean -f -d # remove untracked files and directories

(Warning: This is destructive! Code will be irreversibly lost.)

An alternative to doing the above would be:

$ git add .
$ git reset --hard

And if things aren’t a complete disaster that deserves to be annihilated - for example, perhaps they can serve as a stern reminder in the future - they can be saved prior to destruction with

$ git diff > ~/lessons_learned/rails_mess_1.diff

Enjoy your day-of-the-week :)

Simple:

$ rails console
2.1.0 :001 > Time.now.wday
  => 4   #Thursday
2.1.0 :002 > Date::DAYNAMES
  => ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
2.1.0 :003 > "Enjoy your #{Date::DAYNAMES[Time.now.wday]}."
  => "Enjoy your Thursday."