Module: Tire::Model::Persistence::Attributes::InstanceMethods

Defined in:
lib/tire/model/persistence/attributes.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#idObject

Returns the value of attribute id.



87
88
89
# File 'lib/tire/model/persistence/attributes.rb', line 87

def id
  @id
end

Instance Method Details

#__cast_value(name, value) ⇒ Object

Casts the values according to the :class option set when defining the property, cast Hashes as Hashr[http://rubygems.org/gems/hashr] instances and automatically convert UTC formatted strings to Time.



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/tire/model/persistence/attributes.rb', line 131

def __cast_value(name, value)
  case

    when klass = self.class.property_types[name.to_sym]
      if klass.is_a?(Array) && value.is_a?(Array)
        value.map { |v| klass.first.new(v) }
      else
        klass.new(value)
      end

    when value.is_a?(Hash)
      Hashr.new(value)

    else
      # Strings formatted as <http://en.wikipedia.org/wiki/ISO8601> are automatically converted to Time
      value = Time.parse(value).utc if value.is_a?(String) && value =~ /^\d{4}[\/\-]\d{2}[\/\-]\d{2}T\d{2}\:\d{2}\:\d{2}/
      value
  end
end

#__update_attributes(attributes) ⇒ Object



123
124
125
# File 'lib/tire/model/persistence/attributes.rb', line 123

def __update_attributes(attributes)
  attributes.each { |name, value| send "#{name}=", __cast_value(name, value) }
end

#attribute_namesObject



114
115
116
# File 'lib/tire/model/persistence/attributes.rb', line 114

def attribute_names
  self.class.properties.sort
end

#attributesObject



109
110
111
112
# File 'lib/tire/model/persistence/attributes.rb', line 109

def attributes
  self.class.properties.
    inject( self.id ? {'id' => self.id} : {} ) {|attributes, key| attributes[key] = send(key); attributes}
end

#has_attribute?(name) ⇒ Boolean Also known as: has_property?

Returns:

  • (Boolean)


118
119
120
# File 'lib/tire/model/persistence/attributes.rb', line 118

def has_attribute?(name)
  properties.include?(name.to_s)
end

#initialize(attributes = {}) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/tire/model/persistence/attributes.rb', line 89

def initialize(attributes={})
  # Make a copy of objects in the property defaults hash, so default values
  # such as `[]` or `{ foo: [] }` are preserved.
  #
  property_defaults = self.class.property_defaults.inject({}) do |hash, item|
    key, value = item

    hash[key.to_sym] = if value.respond_to?(:call)
      value.call
    elsif value.class.respond_to?(:new)
      value.clone
    else
      value
    end

    hash
  end
  __update_attributes(property_defaults.merge(attributes))
end