Pages

Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

Wednesday, August 5, 2015

try(), try() again in Rails

In Rails, try() lets you call methods on an object without having to worry about the possibility of that object being nil and thus raising an exception.  Let’s look at some very simple code from a Rails view.

Before

Here’s a simple example of code you might replace with try(). Say you’ve got a Productmodel in your project. A Product may or may not have a known manufacturer, and some links you only want to display if a user is logged in and has administrator rights:
  <!-- products/show.html.erb (before) -->
  <h1><%= @product.name %></h1>

  <% unless @product.manufacturer.nil? %>
    <%= @product.manufacturer.name %>
  <% end %>

  <% if current_user && current_user.is_admin? %>
    <%= link_to 'Edit', edit_product_path(@product) %>
  <% end %>
 try() can help us in a couple of places here:

Wednesday, May 28, 2014

Counters for Partials

Sometimes I like to number rows using a counter when rendering lists of things:
<% @products.each_with_index do |product, i| %>
  <li class="product_<%= i %>"><%= product.name %></li>
<% end %>
They are handy for testing, among other things.
Of course, if the content of the block gets too big I’ll factor it out into a partial. The idiomatic Rails way of doing this is to factor the block contents out into a partial and then render it with the :collectionoption:
< %= render :partial => "product", :collection => @products %>
Which is very clean, except now where do we get our row counter? As it turns out, Rails provides one for us:
  <li class="product_<%= product_counter %>"><%= product.name %></li>
Note the use of product_counter. Rails takes the name of the partial and adds _counter to it when providing the built-in counter.

Wednesday, April 30, 2014

Configure Authlogic to log in with “username” OR “email”



Its very simple to implement Authlogic to use multiple attributes for login.

For example if you want to enable user to login with either email or username, you just need to add the following things to your code:

class UserSession < Authlogic::Session::Base 
  find_by_login_method :find_by_username_or_email
end
and in user.rb
def self.find_by_username_or_email(login)
  User.find_by_username(login) || User.find_by_email(login)
end