Sha256: 543ec0afb8e0bd13c030bef88c1da70e4146db1387176a502c02cb6a1a86f91b

Contents?: true

Size: 1.48 KB

Versions: 3

Compression:

Stored size: 1.48 KB

Contents

module SearchCop
  class Reflection
    attr_accessor :attributes, :options, :aliases, :scope

    def initialize
      self.attributes = {}
      self.options = {}
      self.aliases = {}
    end

    def default_attributes
      keys = options.select { |key, value| value[:default] == true }.keys
      keys = attributes.keys.reject { |key| options[key] && options[key][:default] == false } if keys.empty?
      keys = keys.to_set

      attributes.select { |key, value| keys.include? key }
    end
  end

  class SearchScope
    attr_accessor :name, :model, :reflection

    def initialize(name, model)
      self.model = model
      self.reflection = Reflection.new
    end

    def attributes(*args)
      args.each do |arg|
        attributes_hash arg.is_a?(Hash) ? arg : { arg => arg }
      end 
    end

    def options(key, options = {})
      reflection.options[key.to_s] = (reflection.options[key.to_s] || {}).merge(options)
    end

    def aliases(hash)
      hash.each do |key, value|
        reflection.aliases[key.to_s] = value.respond_to?(:table_name) ? value.table_name : value.to_s
      end
    end

    def scope(&block)
      reflection.scope = block
    end

    private

    def attributes_hash(hash)
      hash.each do |key, value|
        reflection.attributes[key.to_s] = Array(value).collect do |column|
          table, attribute = column.to_s =~ /\./ ? column.to_s.split(".") : [model.name.tableize, column]

          "#{table}.#{attribute}"
        end 
      end 
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
search_cop-1.0.2 lib/search_cop/search_scope.rb
search_cop-1.0.1 lib/search_cop/search_scope.rb
search_cop-1.0.0 lib/search_cop/search_scope.rb