Method: Sohm::Model.attribute
- Defined in:
- lib/sohm.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 < Sohm::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 < Sohm::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.
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 |
# File 'lib/sohm.rb', line 811 def self.attribute(name, cast = nil) if serial_attributes.include?(name) raise ArgumentError, "#{name} is already used as a serial attribute." end 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 |