module NestedAccessors::ClassMethods

Public Instance Methods

nested_accessor(name, *args) click to toggle source

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>
# 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