Method: Sohm::Model.counter
- Defined in:
- lib/sohm.rb
.counter(name) ⇒ Object
Declare a counter. All the counters are internally stored in a different Redis hash, independent from the one that stores the model attributes. Counters are updated with the ‘incr` and `decr` methods, which interact directly with Redis. Their value can’t be assigned as with regular attributes.
Example:
class User < Sohm::Model
counter :points
end
u = User.create
u.incr :points
u.points
# => 1
Note: You can’t use counters until you save the model. If you try to do it, you’ll receive an Sohm::MissingID error.
883 884 885 886 887 888 889 890 891 |
# File 'lib/sohm.rb', line 883 def self.counter(name) counters << name unless counters.include?(name) define_method(name) do return 0 if new? redis.call("HGET", key[:_counters], name).to_i end end |