Sha256: 880ffa0d5384c1b150b3fd10533c6d09a08bef3ca0a213c3520fa02f823a5367

Contents?: true

Size: 896 Bytes

Versions: 6

Compression:

Stored size: 896 Bytes

Contents

module MissileEmitter
  module Searchable
    
    # 搜索条件(klass => {field: scope})
    # eg. {Person => {name_like: scope, older_than: scope}}
    conditions = {}

    MissileEmitter do |klass, key, *, &block|
      (conditions[klass] ||= {}.with_indifferent_access)[key] = block
    end

    extend ActiveSupport::Concern

    included do

      define_singleton_method :search do |hash|
        hash.reduce all do |relation, (key, value)|
          next relation if value.blank? # ignore empty value

          if filter = conditions.fetch(self, {})[key]
            relation.extending do
              # Just for fun :)
              define_method(:_) { value }
            end.instance_exec(value, &filter)
          elsif column_names.include?(key)
            relation.where key => value
          else
            relation
          end
        end
      end
    end

  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
missile_emitter-0.3.6 lib/missile_emitter/searchable.rb
missile_emitter-0.3.5 lib/missile_emitter/searchable.rb
missile_emitter-0.3.4 lib/missile_emitter/searchable.rb
missile_emitter-0.3.3 lib/missile_emitter/searchable.rb
missile_emitter-0.3.2 lib/missile_emitter/searchable.rb
missile_emitter-0.3.1 lib/missile_emitter/searchable.rb