Module: Norton::Helper
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/norton/helper.rb
Defined Under Namespace
Modules: ClassMethods
Instance Method Summary collapse
-
#assign_values(new_values) ⇒ Object
:nodoc.
- #cast_value(type, value) ⇒ Object
-
#norton_mget(*names) ⇒ Model
批量取出当前对象的多个 Norton 字段, 仅仅支持 counter / timestamp.
-
#norton_prefix ⇒ String
Prefix of Redis Key of Norton value, consists with Class name string in plural form and Instance id.
-
#norton_value_key(name) ⇒ String
Returns the final Redis Key of a certain Norton value, teh value will be saved in redis with this value.
Instance Method Details
#assign_values(new_values) ⇒ Object
:nodoc
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/norton/helper.rb', line 109 def assign_values(new_values) new_values.each do |field, val| type = self.class.norton_value_type(field) next unless i[counter ].include?(type) value = cast_value(type, val || try("#{field}_default_value")) instance_variable_set("@#{field}", value) if type == :timestamp && val.nil? && !try("#{field}_default_value").nil? Norton.redis.with do |conn| conn.set(norton_value_key(field), value) end end end end |
#cast_value(type, value) ⇒ Object
85 86 87 88 89 90 |
# File 'lib/norton/helper.rb', line 85 def cast_value(type, value) case type.to_sym when :counter then value.to_i when :timestamp then value.to_i end end |
#norton_mget(*names) ⇒ Model
批量取出当前对象的多个 Norton 字段, 仅仅支持 counter / timestamp
98 99 100 101 102 103 104 105 106 |
# File 'lib/norton/helper.rb', line 98 def norton_mget(*names) values = Norton.redis.with do |conn| conn.mget(names.map { |name| norton_value_key(name) }) end assign_values(names.zip(values).to_h) self end |
#norton_prefix ⇒ String
Prefix of Redis Key of Norton value, consists with Class name string in plural form and Instance id.
Example:
a User instance with id = 1 -> ‘users:1` a HolyLight::Spammer instance with id = 5 -> `holy_light/spammers:5`
61 62 63 64 65 66 |
# File 'lib/norton/helper.rb', line 61 def norton_prefix id = self.id raise Norton::NilObjectId if id.nil? klass = self.class.to_s.pluralize.underscore "#{klass}:#{id}" end |
#norton_value_key(name) ⇒ String
Returns the final Redis Key of a certain Norton value, teh value will be saved in redis with this value.
Example:
a User instance with id = 1 defines a counter named ‘likes_count` -> users:1:likes_count
81 82 83 |
# File 'lib/norton/helper.rb', line 81 def norton_value_key(name) "#{norton_prefix}:#{name}" end |