Module: Fastaccess::ActsWithFastaccessOn::ClassMethods

Defined in:
lib/fastaccess/acts_with_fastaccess_on.rb

Instance Method Summary collapse

Instance Method Details

#acts_with_fastaccess_on(method_name, options = {}) ⇒ Object

registers the pertaining method as one, which return value is provided through redis. This is for fast access of otherwise generated content with a high reading/writing ratio.

Parameters:

  • method_name (Symbol)

    denoting the pertaining method this method shouldn’t be defined beforehand.

  • options (Hash) (defaults to: {})

    is basic options hash. currently has no effect on execution.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/fastaccess/acts_with_fastaccess_on.rb', line 18

def acts_with_fastaccess_on(method_name, options = {})
  Fastaccess.register_on self, method_name, options
  define_singleton_method :method_added do |on_method|
    if Fastaccess.registered? self, on_method
      method = on_method
      alias_name = Fastaccess.alias_for method
      if !method_defined?(alias_name)
        alias_method alias_name, method 
        define_method method do |*args|
          redis_id = Fastaccess.redis_id_for(self, method, args)
          opts = Fastaccess.options_for(self, method)
          content_current = opts[:auto_update] ? Fastaccess.update_check(self) : true
          if Fastaccess.redis.exists(redis_id) && content_current
            response = Fastaccess.redis.get(redis_id)
            begin
              return JSON.parse response
            rescue JSON::ParserError
              return response
            end
          else
            response = method(alias_name).call(*args)
            Fastaccess.update_info self
            Fastaccess.redis.set(redis_id, (response.is_a? String) ? response : response.to_json)
            return response
          end
        end
      end
    end
  end
end