Class: Para::AttributeFieldMappings

Inherits:
Object
  • Object
show all
Defined in:
lib/para/attribute_field_mappings.rb

Constant Summary collapse

UNEDITABLE_ATTRIBUTES =
%w(id component_id created_at updated_at type)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, whitelist_attributes: nil, mappings: nil) ⇒ AttributeFieldMappings

The mappings hash is a form provided hash of attributes and input types mapping that are automatically generated in the form builder and that allows our model field parsers to spot unregistered fields and process them when needed.



12
13
14
15
16
17
18
# File 'lib/para/attribute_field_mappings.rb', line 12

def initialize(model, whitelist_attributes: nil, mappings: nil)
  @model = model
  @whitelist_attributes = whitelist_attributes
  @mappings = mappings || {}

  process_fields!
end

Instance Attribute Details

#fields_hashObject (readonly)

Returns the value of attribute fields_hash.



5
6
7
# File 'lib/para/attribute_field_mappings.rb', line 5

def fields_hash
  @fields_hash
end

#mappingsObject (readonly)

Returns the value of attribute mappings.



5
6
7
# File 'lib/para/attribute_field_mappings.rb', line 5

def mappings
  @mappings
end

#modelObject (readonly)

Returns the value of attribute model.



5
6
7
# File 'lib/para/attribute_field_mappings.rb', line 5

def model
  @model
end

#whitelist_attributesObject (readonly)

Returns the value of attribute whitelist_attributes.



5
6
7
# File 'lib/para/attribute_field_mappings.rb', line 5

def whitelist_attributes
  @whitelist_attributes
end

Instance Method Details

#field_for(field_name, type = nil) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/para/attribute_field_mappings.rb', line 24

def field_for(field_name, type = nil)
  existing_field = fields_hash[field_name]

  if !existing_field || (type && !existing_field.type?(type))
    fields_hash[field_name] = if model.new.respond_to?(field_name)
      build_field_for(field_name, type)
    else
      raise NoMethodError.new(
        "No attribute or method correspond to ##{ field_name } " +
        "in the model #{ model.name }. No field could be created."
      )
    end
  else
    existing_field
  end
end

#fieldsObject



20
21
22
# File 'lib/para/attribute_field_mappings.rb', line 20

def fields
  fields_hash.values
end