Sha256: d9ed740e795a030aaa8d4ca61f89f52c2b40edaa7ca796814a3ff0eecaf7d107

Contents?: true

Size: 1.63 KB

Versions: 1

Compression:

Stored size: 1.63 KB

Contents

module Querifier
  module Queries
    module Where
      def collection
        super
        filter
        @collection
      end

      def filter
        return self if @filtered
        filter_params.each do |(attribute, _)|
          value = filter_value(attribute)
          send("filter_by_#{attribute}", value) if value
        end
        @filtered = true
        self
      end

      def filter_value(key)
        filter_params.fetch(key.to_sym, nil)
      end

      def filter_by(name, value)
        filter_content = filter_value(name)
        @collection = @collection.where("#{name} LIKE ?", "%#{filter_content}%") if filter_content
        self
      end

      def method_missing(message, *args, &block)
        return filter_by(Regexp.last_match(1).to_sym, args.first) if message.to_s =~ /filter_by_(.*)/ # rubocop:disable Performance/RegexpMatch, Metrics/LineLength
        super
      end

      def valid_option?(option)
        self.class.where_attributes.include?(option.to_sym)
      end

      def filter_params
        @filter_params ||=
          params.fetch(Config.where_param, {}).select { |(k, _)| valid_option? k.to_sym }
      end


      def self.included(klass)
        klass.extend(ClassMethods)
      end

      module ClassMethods
        @@where_attributes = []

        def where_attributes(*value)
          return class_variable_set :@@where_attributes, [*value] if value.any?
          begin
            class_variable_get :@@where_attributes
          rescue NameError
            class_variable_set :@@where_attributes, []
            class_variable_get :@@where_attributes
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
querifier-0.2.3 lib/querifier/queries/where.rb