Rails Utility Methods

October 20th, 2008 By: Daniel

Browsing the Rails API I found a few methods I wish I’d known about earlier.

current_page? in ActionView::Helpers::UrlHelper returns “true if the current request URI was generated by the given options.”

  current_page?(:action => 'process')
  # => false
 
  current_page?(:action => 'checkout')
  # => true

reverse_merge! in ActiveSupport::CoreExtensions::Hash::ReverseMerge “allows for reverse merging where its the keys in the calling hash that wins over those in the other_hash.”

So now instead of

  def setup(options = {})
    options = {:income => 0, :expenses => 0}.merge(options)
  end

I can do

  def setup(options = {})
    options.reverse_merge! :income => 0, :expenses => 0
  end

And with ActiveSupport::CoreExtensions::String::Conversions I can stop using the PHP feeling

  Date.parse("10/20/2008")

to the more rubyish

  "10/20/2008".to_date

One Response to “Rails Utility Methods”

  1. Bob Says:

    reverse_merge is awesome. The problem I ran into the other day is if the key has a nil value it doesn’t get overwritten. I can understand why, but kind of lame at the same time.

    {:key=>nil}.reverse_merge(:key=>’value’}
    =>{:key=>nil}

Leave a Reply