Class: Locomotive::API::Forms::BaseForm

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Dirty, ActiveModel::Model, ActiveModel::Serialization
Defined in:
app/api/locomotive/api/forms/base_form.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#_persistedObject

Returns the value of attribute _persisted.



10
11
12
# File 'app/api/locomotive/api/forms/base_form.rb', line 10

def _persisted
  @_persisted
end

#_policyObject

Returns the value of attribute _policy.



10
11
12
# File 'app/api/locomotive/api/forms/base_form.rb', line 10

def _policy
  @_policy
end

Class Method Details

.attributesObject



14
15
16
# File 'app/api/locomotive/api/forms/base_form.rb', line 14

def attributes
  @attributes
end

.attrs(*args) ⇒ Object

Set up accessor methods, and define setters to notify Dirty that they’ve changed.



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'app/api/locomotive/api/forms/base_form.rb', line 20

def attrs(*args)
  options = args.last.is_a?(Hash) ? args.pop : { localized: false }

  @attributes ||= []

  args.each do |name|
    @attributes << define_attribute(name, options[:localized])

    if options[:localized]
      @attributes << define_attribute(:"#{name}_translations")
    end
  end
end

.define_attribute(name, localized = false) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'app/api/locomotive/api/forms/base_form.rb', line 34

def define_attribute(name, localized = false)
  # activemodel
  define_attribute_method(name)

  # getter
  self.send(:attr_reader, name)

  # setter
  define_method(:"#{name}=") do |val|
    if localized && val.is_a?(Hash)
      self.send(:"#{name}_translations=", val)
    else
      set_attribute(name, val)
    end
  end
end

Instance Method Details

#persisted?Boolean

Returns:



62
63
64
# File 'app/api/locomotive/api/forms/base_form.rb', line 62

def persisted?
  false
end

#serializable_hashObject



54
55
56
57
58
59
60
# File 'app/api/locomotive/api/forms/base_form.rb', line 54

def serializable_hash
  changed.sort_by do |name|
    self.class.attributes.index(:"#{name}=")
  end.inject({}) do |hash, attribute|
    hash.merge({ attribute => send(attribute) })
  end.to_h.with_indifferent_access
end

#set_attribute(name, value) ⇒ Object



66
67
68
69
# File 'app/api/locomotive/api/forms/base_form.rb', line 66

def set_attribute(name, value)
  send("#{name}_will_change!") unless send(name) == value
  instance_variable_set("@#{name}", value)
end