Sha256: c0391edf7fa8f62141ec6742402e2c04ed5316d5a74f52f2387ab13142f43fb0

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

require 'active_support/hash_with_indifferent_access'
require 'livelist/rails/filter_criterion'

module Livelist
  module Rails

    class FilterCriteria < HashWithIndifferentAccess
      alias :criteria :values
      alias :find_criteria :[]
      attr_reader :slug

      def initialize(options)
        @filter             = options[:filter]
        @reference_criteria = options[:reference_criteria] || default_reference_criteria
        @reference_criteria = @reference_criteria.call if @reference_criteria.respond_to?(:call)
        @slug               = options[:slug]

        @reference_criteria.each do |reference|
          create_criterion(reference)
        end
      end

      def default_reference_criteria
        @filter.model_class.select("distinct #{@filter.slug}")
      end

      def create_criterion(reference)
        filter_criterion = FilterCriterion.new(:filter => @filter, :criteria => self, :reference => reference)
        self[filter_criterion.slug] = filter_criterion
      end

      def slugs
        criteria.map(&:slug)
      end

      def counts=(counts_hash)
        criteria.each do |criterion|
          criterion.count = counts_hash[criterion.slug.to_s] || 0
        end
      end

      def as_json(params)
        criteria.map do |criterion|
          criterion.as_json(params)
        end
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
livelist-rails-0.0.11 lib/livelist/rails/filter_criteria.rb