module Norton::Helper
Public Instance Methods
assign_values(new_values)
click to toggle source
:nodoc
# File lib/norton/helper.rb, line 129 def assign_values(new_values) new_values.each do |field, val| type = self.class.norton_value_type(field) ivar_name = :"@#{field}" case type when :counter value = cast_value(type, val || try("#{field}_default_value")) instance_variable_set(ivar_name, value) when :timestamp if !val.nil? instance_variable_set(ivar_name, cast_value(type, val)) elsif self.class.norton_values[field][:allow_nil] instance_variable_set(ivar_name, nil) else value = cast_value(type, try("#{field}_default_value")) instance_variable_set(ivar_name, value) self.class.norton_value_redis_pool(field).with do |conn| conn.set(norton_value_key(field), value) end end end end end
cast_value(type, value)
click to toggle source
# File lib/norton/helper.rb, line 97 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)
click to toggle source
批量取出当前对象的多个 Norton
字段, 仅仅支持 counter / timestamp
@param [Array] names 需要检索的字段, 例如: :field1, :field2
@return [Model] 当前对象
# File lib/norton/helper.rb, line 110 def norton_mget(*names) pools_with_name = names.each_with_object({}) do |name, hash| pool = self.class.norton_value_redis_pool(name) hash[pool] ||= [] hash[pool] << name end pools_with_name.each do |pool, fields| values = pool.with do |conn| conn.mget(fields.map { |field| norton_value_key(field) }) end assign_values(fields.zip(values).to_h) end self end
norton_prefix()
click to toggle source
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`
@return [String]
# File lib/norton/helper.rb, line 73 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)
click to toggle source
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
@param [String] name
@return [String]
# File lib/norton/helper.rb, line 93 def norton_value_key(name) "#{norton_prefix}:#{name}" end