Class: ActiveData::Model::Attributes::Attribute

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

Direct Known Subclasses

Collection, Dictionary, Localized, Represents

Instance Attribute Summary

Attributes inherited from Base

#name, #owner

Instance Method Summary collapse

Methods inherited from Base

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

Constructor Details

This class inherits a constructor from ActiveData::Model::Attributes::Base

Instance Method Details

#defaultObject



26
27
28
# File 'lib/active_data/model/attributes/attribute.rb', line 26

def default
  defaultizer.is_a?(Proc) ? evaluate(&defaultizer) : defaultizer
end

#defaultize(value, default_value = nil) ⇒ Object



30
31
32
# File 'lib/active_data/model/attributes/attribute.rb', line 30

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

#enumObject



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/active_data/model/attributes/attribute.rb', line 34

def enum
  source = enumerizer.is_a?(Proc) ? evaluate(&enumerizer) : enumerizer

  case source
  when Range
    source.to_a
  when Set
    source
  else
    Array.wrap(source)
  end.to_set
end

#enumerize(value) ⇒ Object



47
48
49
50
# File 'lib/active_data/model/attributes/attribute.rb', line 47

def enumerize(value)
  set = enum if enumerizer
  value if !set || (set.none? || set.include?(value))
end

#normalize(value) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/active_data/model/attributes/attribute.rb', line 52

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

#readObject



14
15
16
17
18
# File 'lib/active_data/model/attributes/attribute.rb', line 14

def read
  variable_cache(:value) do
    normalize(enumerize(typecast(read_before_type_cast)))
  end
end

#read_before_type_castObject



20
21
22
23
24
# File 'lib/active_data/model/attributes/attribute.rb', line 20

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

#write(value) ⇒ Object



7
8
9
10
11
12
# File 'lib/active_data/model/attributes/attribute.rb', line 7

def write(value)
  return if readonly?
  pollute do
    write_value value
  end
end