Method: Ohm::Model.attribute

Defined in:
lib/ohm.rb

.attribute(name, cast = nil) ⇒ Object

The bread and butter macro of all models. Basically declares persisted attributes. All attributes are stored on the Redis hash.

class User < Ohm::Model
  attribute :name
end

user = User.new(name: "John")
user.name
# => "John"

user.name = "Jane"
user.name
# => "Jane"

A lambda can be passed as a second parameter to add typecasting support to the attribute.

class User < Ohm::Model
  attribute :age, ->(x) { x.to_i }
end

user = User.new(age: 100)

user.age
# => 100

user.age.kind_of?(Integer)
# => true

Check rubydoc.info/github/cyx/ohm-contrib#Ohm__DataTypes to see more examples about the typecasting feature.



1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
# File 'lib/ohm.rb', line 1033

def self.attribute(name, cast = nil)
  attributes << name unless attributes.include?(name)

  if cast
    define_method(name) do
      cast[@attributes[name]]
    end
  else
    define_method(name) do
      @attributes[name]
    end
  end

  define_method(:"#{name}=") do |value|
    @attributes[name] = value
  end
end