Module: Ohm::Typecast::ClassMethods

Defined in:
lib/ohm/contrib/typecast.rb

Instance Method Summary collapse

Instance Method Details

#attribute(name, type = Ohm::Types::String, klass = ) ⇒ Array? Also known as: typecast

Defines a typecasted attribute.

Examples:


class User < Ohm::Model
  include Ohm::Typecast

  attribute :birthday, Date
  attribute :last_login, Time
  attribute :age, Integer
  attribute :spending, Decimal
  attribute :score, Float
end

user = User.new(:birthday => "2000-01-01")
user.birthday.month == 1
# => true

user.birthday.year == 2000
# => true

user.birthday.day == 1
# => true

user = User.new(:age => 20)
user.age - 1 == 19
=> true

Parameters:

  • name (Symbol)

    the name of the attribute to define.

  • type (Class) (defaults to: Ohm::Types::String)

    (defaults to Ohm::Types::String) a class defined in Ohm::Types. You may define custom types in Ohm::Types if you need to.

Returns:

  • (Array)

    the array of attributes already defined.

  • (nil)

    if the attribute is already defined.



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/ohm/contrib/typecast.rb', line 315

def attribute(name, type = Ohm::Types::String, klass = Ohm::Types[type])
  # Primitive types maintain a reference to the original object
  # stored in @_attributes[att]. Hence mutation works for the
  # Primitive case. For cases like Hash, Array where the value
  # is `JSON.parse`d, we need to set the actual Ohm::Types::Hash
  # (or similar) to @_attributes[att] for mutation to work.
  if klass.superclass == Ohm::Types::Primitive
    define_method(name) { klass[read_local(name)] }
  else
    define_method(name) { write_local(name, klass[read_local(name)]) }
  end

  define_method(:"#{name}=") do |value|
    write_local(name, klass[value].to_s)
  end

  attributes << name unless attributes.include?(name)
end