Sha256: 4daf0fcdeecb2ca423b7354799798cfb64c648ddad37ce588d75ef2b70cfa79e

Contents?: true

Size: 847 Bytes

Versions: 6

Compression:

Stored size: 847 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

    define_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 :) With Ruby >= 2.7 you can use _1 instead of _.
            define_method(:_) { value }
          end.instance_exec(value, &filter)
        elsif column_names.include?(key.to_s)
          relation.where key => value
        else
          relation
        end
      end
    end

  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
missile_emitter-0.3.17 lib/missile_emitter/searchable.rb
missile_emitter-0.3.16 lib/missile_emitter/searchable.rb
missile_emitter-0.3.14 lib/missile_emitter/searchable.rb
missile_emitter-0.3.13 lib/missile_emitter/searchable.rb
missile_emitter-0.3.12 lib/missile_emitter/searchable.rb
missile_emitter-0.3.11 lib/missile_emitter/searchable.rb