2011-03-30 20:31:39 -04:00
|
|
|
module Ransack
|
|
|
|
class Predicate
|
2013-08-04 09:13:41 -04:00
|
|
|
attr_reader :name, :arel_predicate, :type, :formatter, :validator,
|
|
|
|
:compound, :wants_array
|
2011-03-30 20:31:39 -04:00
|
|
|
|
|
|
|
class << self
|
2011-06-06 21:32:03 -04:00
|
|
|
|
|
|
|
def names
|
|
|
|
Ransack.predicates.keys
|
|
|
|
end
|
|
|
|
|
2011-03-30 20:31:39 -04:00
|
|
|
def named(name)
|
2011-06-05 14:29:54 -04:00
|
|
|
Ransack.predicates[name.to_s]
|
2011-03-30 20:31:39 -04:00
|
|
|
end
|
|
|
|
|
2011-06-06 21:32:03 -04:00
|
|
|
def detect_and_strip_from_string!(str)
|
2017-08-02 16:32:11 -04:00
|
|
|
detect_from_string str, chomp: true
|
2011-06-06 21:32:03 -04:00
|
|
|
end
|
|
|
|
|
2017-08-02 16:32:11 -04:00
|
|
|
def detect_from_string(str, chomp: false)
|
|
|
|
return unless str
|
2011-06-06 21:32:03 -04:00
|
|
|
|
2017-08-02 16:32:11 -04:00
|
|
|
Ransack.predicates.sorted_names_with_underscores.each do |predicate, underscored|
|
|
|
|
if str.end_with? underscored
|
|
|
|
str.chomp! underscored if chomp
|
|
|
|
return predicate
|
|
|
|
end
|
|
|
|
end
|
2011-06-06 21:32:03 -04:00
|
|
|
|
2017-08-02 16:32:11 -04:00
|
|
|
nil
|
|
|
|
end
|
2011-06-06 21:32:03 -04:00
|
|
|
|
2011-03-30 20:31:39 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def initialize(opts = {})
|
|
|
|
@name = opts[:name]
|
|
|
|
@arel_predicate = opts[:arel_predicate]
|
|
|
|
@type = opts[:type]
|
|
|
|
@formatter = opts[:formatter]
|
2014-05-01 09:55:39 -04:00
|
|
|
@validator = opts[:validator] ||
|
|
|
|
lambda { |v| v.respond_to?(:empty?) ? !v.empty? : !v.nil? }
|
2011-03-30 20:31:39 -04:00
|
|
|
@compound = opts[:compound]
|
2015-03-19 17:01:45 -04:00
|
|
|
@wants_array = opts.fetch(:wants_array,
|
|
|
|
@compound || Constants::IN_NOT_IN.include?(@arel_predicate))
|
2011-03-30 20:31:39 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def eql?(other)
|
|
|
|
self.class == other.class &&
|
|
|
|
self.name == other.name
|
|
|
|
end
|
|
|
|
alias :== :eql?
|
|
|
|
|
|
|
|
def hash
|
|
|
|
name.hash
|
|
|
|
end
|
|
|
|
|
2011-06-06 21:32:03 -04:00
|
|
|
def format(val)
|
|
|
|
if formatter
|
|
|
|
formatter.call(val)
|
|
|
|
else
|
|
|
|
val
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-06-22 22:16:44 -04:00
|
|
|
def validate(vals, type = @type)
|
2014-12-10 13:25:05 -05:00
|
|
|
vals.any? { |v| validator.call(type ? v.cast(type) : v.value) }
|
2011-03-30 20:31:39 -04:00
|
|
|
end
|
|
|
|
|
2016-01-02 13:49:13 -05:00
|
|
|
def negative?
|
|
|
|
@name.include?("not_".freeze)
|
|
|
|
end
|
|
|
|
|
2011-03-30 20:31:39 -04:00
|
|
|
end
|
2014-04-09 23:28:29 -04:00
|
|
|
end
|