Class: Granite::Form::Model::Attributes::Attribute

Inherits:
Base
  • Object
show all
Defined in:
lib/granite/form/model/attributes/attribute.rb

Direct Known Subclasses

Represents

Instance Attribute Summary

Attributes inherited from Base

#type_definition

Instance Method Summary collapse

Methods inherited from Base

#came_from_default?, #came_from_user?, #initialize, #inspect_attribute, #pollute, #query, #readonly?, #reset, #value_present?, #write_value

Constructor Details

This class inherits a constructor from Granite::Form::Model::Attributes::Base

Instance Method Details

#defaultObject



28
29
30
# File 'lib/granite/form/model/attributes/attribute.rb', line 28

def default
  owner.evaluate_if_proc(defaultizer)
end

#defaultize(value, default_value = nil) ⇒ Object



32
33
34
# File 'lib/granite/form/model/attributes/attribute.rb', line 32

def defaultize(value, default_value = nil)
  !defaultizer.nil? && value.nil? ? default_value || default : value
end

#normalize(value) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/granite/form/model/attributes/attribute.rb', line 36

def normalize(value)
  if normalizers.none?
    value
  else
    normalizers.inject(value) do |val, normalizer|
      case normalizer
      when Proc
        owner.evaluate(normalizer, val)
      when Hash
        normalizer.inject(val) do |v, (name, options)|
          Granite::Form.normalizer(name).call(v, options, self)
        end
      else
        Granite::Form.normalizer(normalizer).call(val, {}, self)
      end
    end
  end
end

#readObject



16
17
18
19
20
# File 'lib/granite/form/model/attributes/attribute.rb', line 16

def read
  variable_cache(:value) do
    normalize(type_definition.prepare(read_before_type_cast))
  end
end

#read_before_type_castObject



22
23
24
25
26
# File 'lib/granite/form/model/attributes/attribute.rb', line 22

def read_before_type_cast
  variable_cache(:value_before_type_cast) do
    defaultize(@value_cache)
  end
end

#write(value) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/granite/form/model/attributes/attribute.rb', line 8

def write(value)
  return if readonly?

  pollute do
    write_value value
  end
end