Module: Dynamo::DynamicFields

Defined in:
lib/dynamo/dynamic_fields.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

FIELD_NAME_PATTERN =
/(.+)_field(=)?$/

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/dynamo/dynamic_fields.rb', line 51

def method_missing(sym, *args, &block)
  return super unless sym.match FIELD_NAME_PATTERN

  field_name = $1
  is_setter  = $2.present?
  field      = self.fields.find {|f| f..underscored_name == field_name} || CustomFieldValue.new

  if is_setter
    field.value = args.first
  else
    field.value
  end
end

Class Method Details

.included(base) ⇒ Object



19
20
21
# File 'lib/dynamo/dynamic_fields.rb', line 19

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#attributes=(attrs) ⇒ Object



65
66
67
68
69
70
71
72
73
74
# File 'lib/dynamo/dynamic_fields.rb', line 65

def attributes=(attrs)
  field_attributes = attrs.delete('fields') {{}}

  fields.each do |field|
    field.set_value_from_attributes field_attributes
    fields_will_change! if field.changed?
  end

  super
end

#field_errorsObject



29
30
31
32
33
# File 'lib/dynamo/dynamic_fields.rb', line 29

def field_errors
  self.fields.each_with_object({}) do |f, h|
    h.merge! f.field_errors
  end
end

#fields_metadata=(fields_metadata) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/dynamo/dynamic_fields.rb', line 35

def fields_metadata=()
  self.fields = []

  .each do ||
    self.fields << CustomFieldValue.new(:metadata => )
  end
end

#respond_to_missing?(sym, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
49
# File 'lib/dynamo/dynamic_fields.rb', line 43

def respond_to_missing?(sym, include_private = false)
  return super unless sym.match FIELD_NAME_PATTERN

  field_name = $1

  self.fields.find {|f| f..underscored_name == field_name}.present?
end

#validate_dynamic_fieldsObject



23
24
25
26
27
# File 'lib/dynamo/dynamic_fields.rb', line 23

def validate_dynamic_fields
  self.fields.each do |field|
    self.errors.add(:fields, field.errors) unless field.valid?
  end
end