[Rails] Hash to Obj

Небольшой хак, для использования хеша, как объект…

Для начала создаем модель hash_to_obj.rb, следующего содержания:

class HashToObj
  def initialize(hash)
    hash.each do |k,v|
      #create and initialize an instance variable for this key/value pair
      self.instance_variable_set("@#{k}", v)  
      #create the getter that returns the instance variable
      self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
      #create the setter that sets the instance variable
      self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})


#hash for test
hash = {:key => "value"}
#magick ^_^ 
obj_hash = HashToObj.new(hash)
 #output# => #<HashToObj:0xb6d5a2bc @key="value"> 
 #output# => "value" 

Happy rails coding =_)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s