Class: Datory::Attributes::Form

Inherits:
Object
  • Object
show all
Defined in:
lib/datory/attributes/form.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context, model) ⇒ Form

Returns a new instance of Form.



8
9
10
11
# File 'lib/datory/attributes/form.rb', line 8

def initialize(context, model)
  @context = context
  @model = model
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



6
7
8
# File 'lib/datory/attributes/form.rb', line 6

def model
  @model
end

Instance Method Details

#invalid?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/datory/attributes/form.rb', line 59

def invalid?
  !valid?
end

#serializeObject



47
48
49
# File 'lib/datory/attributes/form.rb', line 47

def serialize
  @serialize ||= @context.serialize(model)
end

#targetObject



13
14
15
# File 'lib/datory/attributes/form.rb', line 13

def target
  @context
end

#update(**attributes) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/datory/attributes/form.rb', line 17

def update(**attributes)
  if model_collection?
    raise_misuse "The `update` method cannot be used with a collection. Instead, use the `update_by` method."
  end

  found_keys = model.send(:keys) & attributes.keys

  reset!

  model.send(:merge!, attributes.slice(*found_keys))
end

#update_by(index, **attributes) ⇒ Object

rubocop:disable Metrics/MethodLength



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/datory/attributes/form.rb', line 29

def update_by(index, **attributes) # rubocop:disable Metrics/MethodLength
  unless model_collection?
    raise_misuse "The `update_by` method cannot be used without a collection. Instead, use the `update` method."
  end

  reset!

  model.map!.with_index do |model_item, model_index|
    if model_index == index
      found_keys = model_item.send(:keys) & attributes.keys

      model_item.send(:merge, attributes.slice(*found_keys))
    else
      model_item
    end
  end
end

#valid?Boolean

Returns:

  • (Boolean)


51
52
53
54
55
56
57
# File 'lib/datory/attributes/form.rb', line 51

def valid?
  serialize

  true
rescue Datory::Exceptions::SerializationError
  false
end