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



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

def abbr
  options[:abbr]
end

#abbr?Boolean

Returns:



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

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

#defaultObject



29
30
31
32
33
34
35
# File 'lib/toy/attribute.rb', line 29

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

#default?Boolean

Returns:



37
38
39
# File 'lib/toy/attribute.rb', line 37

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

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

Returns:



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

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:



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

def persisted?
  !virtual?
end

#persisted_nameObject



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

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:



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

def virtual?
  @virtual
end