Don't miss

I created an open source development tool to quickly & dynamically mock API endpoints. Check it out at GitHub: DuckRails

Heads up

I will no longer maintain arubystory. For new posts, find me at my personal blog. CU there!

Tuesday, May 26, 2015

Ruby & Rails - Cool stuff & tips - S15E01


It's been a while since my last post, I didn't have the time to prepare a tutorial but I'm going to describe some stuff I thought they worth to be mentioned.




Arrays: map & each_with_index


I knew I could iterate through my array's items with an index of their position using the each_with_index method like this:
['a', 'b', 'c'].each_with_index do { |item, index|
  puts "#{index}-#{item}"
}

What is cool though, is the fact that you can use that index while mapping the elements to new objects. Here's how:
['a', 'b', 'c'].each_with_index.map { |item, index|
  { :letter => item,
    :position => index }
}




Views: cycle is not even odd


There have been times I needed to assign a special CSS class to an HTML table's rows based on their index. To accomplish that, I used the each_with_index method on the Array resulting to something like this:
<% an_array.each_with_index do |element, index| %>
  <tr class="<%= index.odd? ? 'odd' : 'even' %>">
    <td>...</td>
  </tr>
<% end %>

Well, say hello to Rails' cycle view helper method. Use this method in an iteration block passing your miscellaneous values (not limited to only two) and let Rails use each of them repeatedly to each iteration. Here's the above piece of code altered to use the cycle method:
<% an_array.each do |item| %>
  <tr class="<%= cycle('odd','even') %>">
    <td>...</td>
  </tr>
<% end %>

Read more about this method and ways of reseting the cycle here.

Nil: don't be afraid to try


Before I learn about the rail's try method, I made heavy use of code like the following:
if @person.present? && @person.a_property == 'foo'
  ..
end

or:

<% if @an_array.present? %>
  <% @an_array.each do |item| %>
    ...
  <% end %>
<% end %>

Well, you can write this in a simpler way by just trying to call the method you want with a change like this:
if @person.try(:a_property) == 'foo'
   ...
end

and:
<% @an_array.try(:each) do |item| %>
  ...
<% end %>


Post a Comment