Module: HashToObject
- Defined in:
- lib/hash_to_object.rb
Constant Summary collapse
- VERSION =
'0.1.0'
Class Method Summary collapse
Instance Method Summary collapse
- #build_class_string(class_string) ⇒ Object
- #build_new_object(class_string, hash_parameters) ⇒ Object
- #define_attribute(key, value) ⇒ Object
- #load_settings ⇒ Object
- #metaclass ⇒ Object
- #objectify(hash_parameters) ⇒ Object
Class Method Details
.build_new_object ⇒ Object
7 |
# File 'lib/hash_to_object.rb', line 7 alias_method :build_new_object, :build_new_object |
Instance Method Details
#build_class_string(class_string) ⇒ Object
23 24 25 26 27 28 29 30 31 32 |
# File 'lib/hash_to_object.rb', line 23 def build_class_string(class_string) @settings ||= load_settings class_string = class_string.singularize.underscore if @settings && @settings.send(class_string.to_sym) @settings.send(class_string.to_sym) else "#{self.class}::#{class_string.singularize.camelcase}" end end |
#build_new_object(class_string, hash_parameters) ⇒ Object
34 35 36 |
# File 'lib/hash_to_object.rb', line 34 def build_new_object(class_string, hash_parameters) class_string.constantize.new(hash_parameters) end |
#define_attribute(key, value) ⇒ Object
38 39 40 41 |
# File 'lib/hash_to_object.rb', line 38 def define_attribute(key, value) .send :attr_accessor, key.underscore send "#{key}=".underscore.to_sym, value end |
#load_settings ⇒ Object
49 50 51 52 |
# File 'lib/hash_to_object.rb', line 49 def load_settings #implement this nil end |
#metaclass ⇒ Object
43 44 45 46 47 |
# File 'lib/hash_to_object.rb', line 43 def class << self self end end |
#objectify(hash_parameters) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/hash_to_object.rb', line 10 def objectify(hash_parameters) hash_parameters.each do |key, value| if value.is_a?(Array) objects = value.map{|item| build_new_object(build_class_string(key), item)} define_attribute(key, objects) elsif value.is_a?(Hash) define_attribute(key, build_new_object(build_class_string(key), value)) else define_attribute(key.to_s, value) end end end |