Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jake Varghese http://www.djdossiers.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Hash Referencing Hack for Ruby

Hash Hacks:
1. Method Missing hack to allow easy referencing.
I can never remember whether the Hash i am playing with has symbols for keys or
strings. I also dont like typing the brackets (not all text editors have the
cool "close brace" feature). That's why i came up with this method missing hack.
Instead of explaining what it does, I'll just show you.

Example:
hsh = {"project"=>
{ "prototype_url"=>nil,
"designer_id"=>2,
"finished_at"=>nil, "phone_number"=>"512225555",
"website"=>"http://www.ggg.com",
"first_name"=>"test",
}
}
hsh.project
#=> {"prototype_url"=>nil, "designer_id"=>2, "finished_at"=>nil, "phone_number"=>"512225555", "website"=>"http://www.ggg.com", "first_name"=>"test"}

hsh.project.prototype_url #=> nil
hsh.project.designer_id #=> 2
hsh.project.first_name #=> test

   1  
   2  class Hash    		
   3    def method_missing(method_id, *args, &block)
   4      method_name = method_id.to_s
   5      check = self.stringify_keys
   6      if check.keys.include?(method_name)
   7        check[method_name]
   8      else
   9        super
  10      end
  11    end
  12  end
  13  



I have packaged this and other useful hacks into a plugin at http://blog.djdossiers.com/articles/2007/03/31/new-rails-plugin-jakes-toolbox

Peace

--jake
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS