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

79 lines
1.8 KiB
Ruby
Raw 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,
:compound, :wants_array
2011-03-31 00:31:39 +00:00
class << self
def names
Ransack.predicates.keys
end
def names_by_decreasing_length
2013-08-04 13:13:41 +00:00
names.sort { |a,b| b.length <=> a.length }
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)
if p = detect_from_string(str)
2014-11-21 19:03:20 +00:00
str.sub! /_#{p}$/, Constants::EMPTY
p
end
end
def detect_from_string(str)
2013-12-07 00:51:55 +00:00
names_by_decreasing_length.detect { |p| str.end_with?("_#{p}") }
end
# def name_from_attribute_name(attribute_name)
# names_by_decreasing_length.detect {
# |p| attribute_name.to_s.match(/_#{p}$/)
# }
# end
# def for_attribute_name(attribute_name)
# self.named(detect_from_string(attribute_name.to_s))
# 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[:wants_array] == true || @compound ||
2014-11-21 19:03:20 +00:00
Constants::IN_NOT_IN.include?(@arel_predicate)
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
end
end