Skip to content

Instantly share code, notes, and snippets.

@phiggins
Created September 9, 2012 20:55
Show Gist options
  • Save phiggins/3687249 to your computer and use it in GitHub Desktop.
Save phiggins/3687249 to your computer and use it in GitHub Desktop.
Rails tricks
One that seems to surprise a lot of people is Hash.from_xml:
> hash = {:foo => 'bar', :baz => 'qux'}
=> {:foo=>"bar", :baz=>"qux"}
> hash.to_xml
=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n
<foo>bar</foo>\n <baz>qux</baz>\n</hash>\n"
> Hash.from_xml(hash.to_xml)
=> {"hash"=>{"foo"=>"bar", "baz"=>"qux"}}
Hash instances also have some added methods that do handy things, like
#stringify_keys / #symbolize_keys and #slice:
> Hash.from_xml(hash.to_xml)['hash'].symbolize_keys
=> {:foo=>"bar", :baz=>"qux"}
> hash.stringify_keys
=> {"foo"=>"bar", "baz"=>"qux"}
> hash.slice(:foo, :bar, :lol)
=> {:foo=>"bar"}
All of Ruby's assorted time classes (Time, Date, DateTime) have some
handy helpers like #beginning_of_month:
> Time.now
=> 2012-09-09 03:19:45 -0700
> Time.now.beginning_of_month
=> 2012-09-01 00:00:00 -0700
That one also works for "end_of_X" and replacing month with day, week,
quarter and year.
Also on ruby's time classes, #to_s will take a symbol argument that
tells which predefined format to render it in:
> Time.now
=> 2012-09-09 03:22:24 -0700
> Time.now.to_s(:db)
=> "2012-09-09 03:22:29"
> Time.now.to_s(:long)
=> "September 9, 2012"
> Date.today
=> Sun, 09 Sep 2012
> Date.today.to_s(:db)
=> "2012-09-09"
> Date.today.to_s(:long)
=> "September 9, 2012"
There are a few of these predefined, and you can even define your own
formats using #strftime strings or by passing a proc (example borrowed
from rails docs):
> Date::DATE_FORMATS[:month_and_year] = "%B %Y"
=> "%B %Y"
> Date::DATE_FORMATS[:short_ordinal] = lambda { |date|
date.strftime("%B #{date.day.ordinalize}") }
=> #<Proc:0x000000056284c8@(irb):25 (lambda)>
> Date.today.to_s(:month_and_year)
=> "September 2012"
> Date.today.to_s(:short_ordinal)
=> "September 9th"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment