Skip to content

Instantly share code, notes, and snippets.

@glucero
Created February 16, 2012 19:29
Show Gist options
  • Select an option

  • Save glucero/1847165 to your computer and use it in GitHub Desktop.

Select an option

Save glucero/1847165 to your computer and use it in GitHub Desktop.
Hash#to_class
class Hash
def to_class(name, namespace='Object')
hash = self
namespace = Kernel.const_get namespace.capitalize
name = name.capitalize
namespace.const_get(name).new hash
rescue Exception => err
namespace.const_set(name, Class.new do
attr_accessor *hash.keys
def valid?() true end
def initialize(hash)
hash.each do |key, val|
instance_variable_set "@#{key}", val
end
end
end).new hash
end
end
person_hash = { 'first_name' => 'Gino', 'last_name' => 'Lucero', 'age' => 34, 'sex' => 'M' }
person = person_hash.to_class('person')
person.inspect
#<Person:0x1099d3640 @first_name="Gino", @last_name="Lucero", @age=34, @sex="M">
person.valid?
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment