Sha256: 32f2c1c19e39638058cd2a754e618e2ac235bd4dbe23e120faf6c2f1c8d26ac9

Contents?: true

Size: 1.72 KB

Versions: 1

Compression:

Stored size: 1.72 KB

Contents

require 'autocompl/repository'

module Autocompl
  module Base
    def self.included(target)
      target.extend Autocompl::Base::ClassMethods
      target.send :include, Autocompl::Repository
    end

    module ClassMethods
      BASE_CACHE_KEY = 'autocomplete_cache'.freeze

      def autocomplete(options = {})
        define_method('autocomplete_endpoint') do
          render json: [] if params[:term].nil?
          render json: [] if options.nil?
          if cacheable?
            items = Rails.cache.fetch(get_cache_key(options), expires_in: cache_expire) { get_items(options) }
          else
            items = get_items(options)
          end
          render json: items
        end
      end
    end

    def get_items(options)
      klasses = options.keys
      items = []
      for klass in klasses
        columns = options[klass].instance_of?(Array) ? options[klass] : [] << options[klass]
        items.concat(get_collection(klass, columns))
      end
      items
    end

    def cacheable?
      Rails.application.config.cache_store.present? && Rails.application.config.cache_autocomplete
    end

    def cache_expire
      Rails.application.config.autocomplete_cache_expire
    end

    def get_cache_key(options)
      ClassMethods::BASE_CACHE_KEY + ':' + get_model_cache_key(options)
    end

    def get_model_cache_key(options)
      klasses = options.keys
      cache_key = ''
      klasses.each_with_index do |klass, index|
        cache_key.concat('_and_') if index > 0
        cache_key.concat(klass.to_s)
        columns = options[klass].instance_of?(Array) ? options[klass] : [] << options[klass]
        for column in columns
          cache_key.concat('_' + column.to_s)
        end
      end
      cache_key
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
autocompl-0.2.0 lib/autocompl/base.rb