module Looksist::Core::ClassMethods

Attributes

lookup_attributes[RW]

Public Instance Methods

lookup(what, opts) click to toggle source
# File lib/looksist/core.rb, line 10
def lookup(what, opts)
  @lookup_attributes ||= {}
  unless opts.keys.all? { |k| [:using, :bucket_name, :as].include? k }
    raise 'Incorrect usage: Invalid parameter specified'
  end
  using, bucket_name, as = opts[:using], opts[:bucket_name] || opts[:using], opts[:as]
  if what.is_a? Array
    setup_composite_lookup(bucket_name, using, what, as)
  else
    alias_what = find_alias(as, what)
    @lookup_attributes[alias_what] = opts[:using]
    define_method(alias_what) do
      result = Looksist.redis_service.send("#{__entity__(bucket_name)}_for", self.send(using).try(:to_s))
      begin
        JSON.parse(result)[what.to_s]
      rescue
        result
      end
    end
  end
end

Private Instance Methods

find_alias(as_map, what) click to toggle source
# File lib/looksist/core.rb, line 43
def find_alias(as_map, what)
  (as_map and as_map.has_key?(what)) ? as_map[what].to_sym : what
end
setup_composite_lookup(bucket, using, what, as) click to toggle source
# File lib/looksist/core.rb, line 33
def setup_composite_lookup(bucket, using, what, as)
  what.each do |method_name|
    alias_method_name = find_alias(as, method_name)
    define_method(alias_method_name) do
      JSON.parse(Looksist.redis_service.send("#{__entity__(bucket)}_for", self.send(using).try(:to_s)) || '{}')[method_name.to_s]
    end
    @lookup_attributes[alias_method_name] = using
  end
end