Class: Toy::Attribute

Inherits:
Object show all
Defined in:
lib/toy/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, name, type, options = {}) ⇒ Attribute

Returns a new instance of Attribute.



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/toy/attribute.rb', line 5

def initialize(model, name, type, options={})
  options.assert_valid_keys(:default, :virtual, :abbr)

  @model, @name, @type, @options = model, name.to_s, type, options
  @virtual = options.fetch(:virtual, false)

  if abbr?
    options[:abbr] = abbr.to_s
    model.alias_attribute(abbr, name)
  end

  model.attributes[name.to_s] = self
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



3
4
5
# File 'lib/toy/attribute.rb', line 3

def model
  @model
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/toy/attribute.rb', line 3

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/toy/attribute.rb', line 3

def options
  @options
end

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/toy/attribute.rb', line 3

def type
  @type
end

Instance Method Details

#abbrObject



58
59
60
# File 'lib/toy/attribute.rb', line 58

def abbr
  options[:abbr]
end

#abbr?Boolean

Returns:



54
55
56
# File 'lib/toy/attribute.rb', line 54

def abbr?
  options.key?(:abbr)
end

#defaultObject



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/toy/attribute.rb', line 29

def default
  if options.key?(:default)
    default = options[:default]
    if default.respond_to?(:call)
      backwards_compatible_call(default)
    else
      default
    end
  else
    type.respond_to?(:store_default) ? type.store_default : nil
  end
end

#default?Boolean

Returns:



42
43
44
# File 'lib/toy/attribute.rb', line 42

def default?
  options.key?(:default) || type.respond_to?(:store_default)
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:



66
67
68
69
70
# File 'lib/toy/attribute.rb', line 66

def eql?(other)
  self.class.eql?(other.class) &&
    model == other.model &&
    name  == other.name
end

#from_store(value) ⇒ Object



19
20
21
22
# File 'lib/toy/attribute.rb', line 19

def from_store(value)
  value = default if default? && value.nil?
  type.from_store(value, self)
end

#persisted?Boolean

Returns:



50
51
52
# File 'lib/toy/attribute.rb', line 50

def persisted?
  !virtual?
end

#persisted_nameObject



62
63
64
# File 'lib/toy/attribute.rb', line 62

def persisted_name
  abbr? ? abbr : name
end

#to_store(value) ⇒ Object



24
25
26
27
# File 'lib/toy/attribute.rb', line 24

def to_store(value)
  value = default if default? && value.nil?
  type.to_store(value, self)
end

#virtual?Boolean

Returns:



46
47
48
# File 'lib/toy/attribute.rb', line 46

def virtual?
  @virtual
end