Created
February 16, 2012 19:29
-
-
Save glucero/1847165 to your computer and use it in GitHub Desktop.
Hash#to_class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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