Module: DecoLite::FieldInformable

Included in:
HashLoadable
Defined in:
lib/deco_lite/field_informable.rb

Overview

Creates and returns a hash given the parameters that are used to dynamically create fields and assign values to a model.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#field_infoObject

Returns the value of attribute field_info.



74
75
76
# File 'lib/deco_lite/field_informable.rb', line 74

def field_info
  @field_info
end

Class Method Details

.get_field_info(hash:, namespace: nil, dig: [], field_info: {}) ⇒ Object

This method simply navigates the payload hash received and creates qualified hash key names that can be used to verify/map to our field names in this model. This can be used to qualify nested hash fields and saves us some headaches if there are nested field names with the same name:

given:

hash = {

first_name: 'first_name',
...
address: {
  street: '',
  ...
}

}

get_field_info(hash: hash) #=>

:first_name=>{:field_name=>:first_name, :dig=>[],
...
:address_street=>:dig=>[:address],
...

}

The generated, qualified field names expected to map to our model, because we named them as such.

:field_name is the actual, unqualified field name found in the payload hash sent. :dig is the hash key by which :field_name can be found in the payload hash if need be -

retained across recursive calls.


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/deco_lite/field_informable.rb', line 38

def get_field_info(hash:, namespace: nil, dig: [], field_info: {})
  hash.each do |key, value|
    if value.is_a? Hash
      get_field_info hash: value,
                     namespace: namespace,
                     dig: dig << key,
                     field_info: field_info
      dig.pop
    else
      set_field_info!(field_info: field_info,
                      key: key,
                      namespace: namespace,
                      dig: dig)
    end
  end

  field_info
end

.merge_field_info!(field_info:) ⇒ Object



66
67
68
# File 'lib/deco_lite/field_informable.rb', line 66

def merge_field_info!(field_info:)
  @field_info.merge!(field_info)
end

.set_field_info!(field_info:, key:, namespace:, dig:) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/deco_lite/field_informable.rb', line 57

def set_field_info!(field_info:, key:, namespace:, dig:)
  field_key = [namespace, *dig, key].compact.join('_').to_sym

  field_info[field_key] = {
    field_name: key,
    dig: dig.dup
  }
end

Instance Method Details

#field_namesObject



70
71
72
# File 'lib/deco_lite/field_informable.rb', line 70

def field_names
  field_info&.keys || []
end