Sha256: 1e1651de3159c616f8b9108863e99e01c75608990fbccbcc5339a2932dcd0960

Contents?: true

Size: 1.72 KB

Versions: 1

Compression:

Stored size: 1.72 KB

Contents

module Looksist
  module Core
    extend ActiveSupport::Concern
    include Looksist::Common

    module ClassMethods
      def lookup(what, opts)
        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)
          self.lookup_attributes << alias_what
          define_method(alias_what) do
            Looksist.redis_service.send("#{__entity__(bucket_name)}_for", self.send(using).try(:to_s))
          end
        end
      end

      private
      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
          self.lookup_attributes << alias_method_name
        end
      end

      def find_alias(as_map, what)
        (as_map and as_map.has_key?(what)) ? as_map[what].to_sym : what
      end
    end


    def as_json(opts)
      Looksist.driver.json_opts(self, opts)
    end

    included do |base|
      base.class_attribute :lookup_attributes
      base.lookup_attributes = []
    end

  end

  module Serializers
    class Her
      class << self
        def json_opts(obj, _)
          obj.attributes.merge(obj.class.lookup_attributes.each_with_object({}) { |a, acc| acc[a] = obj.send(a) })
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
looksist-0.2.2 lib/looksist/core.rb