Class: FormObj::ModelMapper::ModelAttribute::Item

Inherits:
Object
  • Object
show all
Defined in:
lib/form_obj/model_mapper/model_attribute/item.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, klass:, hash:, array:) ⇒ Item

Returns a new instance of Item.



13
14
15
16
17
18
19
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 13

def initialize(name:, klass:, hash:, array:)
  @array = array
  @hash = hash
  @hash_item = name[0] == ':'
  @name = (name[0] == ':' ? name[1..-1] : name).to_sym
  @klass = klass || @name.to_s.classify
end

Instance Attribute Details

#hashObject

Returns the value of attribute hash.



10
11
12
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 10

def hash
  @hash
end

#hash_itemObject

Returns the value of attribute hash_item.



11
12
13
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 11

def hash_item
  @hash_item
end

#nameObject (readonly)

Returns the value of attribute name.



11
12
13
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 11

def name
  @name
end

Instance Method Details

#create_arrayObject



33
34
35
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 33

def create_array
  []
end

#create_modelObject



25
26
27
28
29
30
31
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 25

def create_model
  if @hash
    {}
  else
    (@klass.is_a?(String) ? @klass.constantize : @klass).try(:new)
  end
end

#read_errors_from_model(model) ⇒ Object



66
67
68
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 66

def read_errors_from_model(model)
  @hash_item ? [] : model.errors[@name]
end

#read_from_model(model, create_nested_model_if_nil: false) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 37

def read_from_model(model, create_nested_model_if_nil: false)
  return nil if model.nil?

  result = if @hash_item
             model[hash_attribute_name(model, @name)]
           else
             model.send(@name)
           end

  if result.nil? && create_nested_model_if_nil
    result = @array ? create_array : create_model
    write_to_model(model, result)
  end

  result
end

#to_hash(value) ⇒ Object



62
63
64
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 62

def to_hash(value)
  { @name => value }
end

#write_to_model(model, value) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/form_obj/model_mapper/model_attribute/item.rb', line 54

def write_to_model(model, value)
  if @hash_item
    model[hash_attribute_name(model, @name)] = value
  else
    model.send("#{@name}=", value)
  end
end