2011-03-31 00:31:39 +00:00
|
|
|
module Ransack
|
|
|
|
class Predicate
|
2011-07-15 11:16:38 +00:00
|
|
|
attr_reader :name, :arel_predicate, :type, :formatter, :validator, :compound, :wants_array
|
2011-03-31 00:31:39 +00:00
|
|
|
|
|
|
|
class << self
|
2011-06-07 01:32:03 +00:00
|
|
|
|
|
|
|
def names
|
|
|
|
Ransack.predicates.keys
|
|
|
|
end
|
|
|
|
|
|
|
|
def names_by_decreasing_length
|
|
|
|
names.sort {|a,b| b.length <=> a.length}
|
|
|
|
end
|
|
|
|
|
2011-03-31 00:31:39 +00:00
|
|
|
def named(name)
|
2011-06-05 18:29:54 +00:00
|
|
|
Ransack.predicates[name.to_s]
|
2011-03-31 00:31:39 +00:00
|
|
|
end
|
|
|
|
|
2011-06-07 01:32:03 +00:00
|
|
|
def detect_and_strip_from_string!(str)
|
|
|
|
names_by_decreasing_length.detect {|p| str.sub!(/_#{p}$/, '')}
|
|
|
|
end
|
|
|
|
|
|
|
|
def detect_from_string(str)
|
|
|
|
names_by_decreasing_length.detect {|p| str.match(/_#{p}$/)}
|
|
|
|
end
|
|
|
|
|
|
|
|
def name_from_attribute_name(attribute_name)
|
|
|
|
names_by_decreasing_length.detect {|p| attribute_name.to_s.match(/_#{p}$/)}
|
|
|
|
end
|
|
|
|
|
2011-03-31 00:31:39 +00:00
|
|
|
def for_attribute_name(attribute_name)
|
2011-06-07 01:32:03 +00:00
|
|
|
self.named(detect_from_string(attribute_name.to_s))
|
2011-03-31 00:31:39 +00:00
|
|
|
end
|
2011-06-07 01:32:03 +00:00
|
|
|
|
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]
|
2011-07-17 14:46:30 +00:00
|
|
|
@validator = opts[:validator] || lambda { |v| v.respond_to?(:empty?) ? !v.empty? : !v.nil? }
|
2011-03-31 00:31:39 +00:00
|
|
|
@compound = opts[:compound]
|
2011-07-15 11:16:38 +00:00
|
|
|
@wants_array = @compound || ['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
|
|
|
|
|
2011-06-07 01:32:03 +00:00
|
|
|
def format(val)
|
|
|
|
if formatter
|
|
|
|
formatter.call(val)
|
|
|
|
else
|
|
|
|
val
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2011-06-23 02:16:44 +00:00
|
|
|
def validate(vals, type = @type)
|
|
|
|
vals.select {|v| validator.call(type ? v.cast(type) : v.value)}.any?
|
2011-03-31 00:31:39 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
end
|