Module: NestedAccessors::ClassMethods

Defined in:
lib/nested_accessors.rb

Instance Method Summary collapse

Instance Method Details

#nested_accessor(name, *args) ⇒ Object

Creates new method nested_accessor for adding dynamic accessors to nested hashes, using:

<tt>nested_accessor :pz_settings, confirmation_token: String, subsettings: { foo: String, bar: Integer }</tt>


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/nested_accessors.rb', line 13

def nested_accessor(name, *args)
  self.class_eval do
    serialize name, Hash
  end

  args.each do |an_arg|
    if an_arg.is_a? Hash
      # nested_accessor :info, address: [:foo]
      an_arg.each do |subroot,propnames|
        if propnames.is_a? Array  # eg "address: [:city, :zipcode]"
          define_first_level_nesting_methods_for_subroot(name, subroot, Hash, propnames)
        elsif propnames == Array  # eg "address: Array"
          define_first_level_nesting_methods_for_subroot(name, subroot, Array)
        elsif propnames.is_a? Symbol  # eg "auth: :facebook"
          define_first_level_nesting_methods_for_subroot(name, subroot, Hash, [propnames])
        elsif propnames.is_a? Hash  # eg "subregion: { address: [:street, :city] }"
          propnames.each do |subsubroot,subpropnames|
            define_first_level_nesting_methods_for_subroot(name, subroot, Hash, [subsubroot])
            define_second_level_nesting_methods(subroot, subsubroot, subpropnames)
          end
        end
      end
    elsif an_arg.is_a? Array
      an_arg.each do |a_propname|
        define_first_level_nesting_methods_for_property(name, a_propname)
      end
    elsif an_arg.is_a? Symbol
      define_first_level_nesting_methods_for_property(name, an_arg)
    end
  end
end