Module: Norton::Helper

Extended by:
ActiveSupport::Concern
Defined in:
lib/norton/helper.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#assign_values(new_values) ⇒ Object

:nodoc



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# 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) ⇒ Object



97
98
99
100
101
102
# 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) ⇒ Model

批量取出当前对象的多个 Norton 字段, 仅仅支持 counter / timestamp

Parameters:

  • names (Array)

    需要检索的字段, 例如: :field1, :field2

Returns:

  • (Model)

    当前对象



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# 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_prefixString

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`

Returns:

  • (String)

Raises:



73
74
75
76
77
78
# 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) ⇒ 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

Parameters:

  • name (String)

Returns:

  • (String)


93
94
95
# File 'lib/norton/helper.rb', line 93

def norton_value_key(name)
  "#{norton_prefix}:#{name}"
end