activerecord-hackery--ransack/lib/ransack/predicate.rb

76 lines
1.6 KiB
Ruby
Raw Permalink Normal View History

2011-03-31 00:31:39 +00:00
module Ransack
class Predicate
2013-08-04 13:13:41 +00:00
attr_reader :name, :arel_predicate, :type, :formatter, :validator,
2019-11-05 15:54:02 +00:00
:compound, :wants_array, :case_insensitive
2011-03-31 00:31:39 +00:00
class << self
def names
Ransack.predicates.keys
end
2011-03-31 00:31:39 +00:00
def named(name)
Ransack.predicates[name.to_s]
2011-03-31 00:31:39 +00:00
end
def detect_and_strip_from_string!(str)
2017-08-02 20:32:11 +00:00
detect_from_string str, chomp: true
end
2017-08-02 20:32:11 +00:00
def detect_from_string(str, chomp: false)
return unless str
2017-08-02 20:32:11 +00: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
2017-08-02 20:32:11 +00:00
nil
end
2011-03-31 00:31:39 +00:00
end
def initialize(opts = {})
@name = opts[:name]
@arel_predicate = opts[:arel_predicate]
@type = opts[:type]
@formatter = opts[:formatter]
@validator = opts[:validator] ||
lambda { |v| v.respond_to?(:empty?) ? !v.empty? : !v.nil? }
2011-03-31 00:31:39 +00:00
@compound = opts[:compound]
@wants_array = opts.fetch(:wants_array,
@compound || Constants::IN_NOT_IN.include?(@arel_predicate))
2019-11-05 15:54:02 +00:00
@case_insensitive = opts[:case_insensitive]
2011-03-31 00:31:39 +00:00
end
def eql?(other)
self.class == other.class &&
self.name == other.name
end
alias :== :eql?
def hash
name.hash
end
def format(val)
if formatter
formatter.call(val)
else
val
end
end
def validate(vals, type = @type)
vals.any? { |v| validator.call(type ? v.cast(type) : v.value) }
2011-03-31 00:31:39 +00:00
end
2016-01-02 18:49:13 +00:00
def negative?
@name.include?("not_".freeze)
end
2011-03-31 00:31:39 +00:00
end
end