mirror of
https://github.com/activerecord-hackery/ransack.git
synced 2022-11-09 13:47:45 -05:00
381a83cebe
from using global constants to frozen strings (cc @avit). It's not pretty, but it's faster and better for understanding the code without having to look up what the special constants represent. From the discussion in #530: "Things are evolving, but with Ruby 2.2 here is my current understanding: - I believe you are correct that the strings inside the array could benefit from freezing, in hot spots. - Freezing a string may now be faster than looking up a frozen string constant. So, it might make sense now in Ransack master and upcoming releases, to optimize for Ruby 2.2+ and stop using frozen constants, and replace them with frozen strings or symbols." Closes #530.
78 lines
1.7 KiB
Ruby
78 lines
1.7 KiB
Ruby
module Ransack
|
|
class Predicate
|
|
attr_reader :name, :arel_predicate, :type, :formatter, :validator,
|
|
:compound, :wants_array
|
|
|
|
class << self
|
|
|
|
def names
|
|
Ransack.predicates.keys
|
|
end
|
|
|
|
def names_by_decreasing_length
|
|
names.sort { |a, b| b.length <=> a.length }
|
|
end
|
|
|
|
def named(name)
|
|
Ransack.predicates[name.to_s]
|
|
end
|
|
|
|
def detect_and_strip_from_string!(str)
|
|
if p = detect_from_string(str)
|
|
str.sub! /_#{p}$/, ''.freeze
|
|
p
|
|
end
|
|
end
|
|
|
|
def detect_from_string(str)
|
|
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
|
|
|
|
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? }
|
|
@compound = opts[:compound]
|
|
@wants_array = opts.fetch(:wants_array,
|
|
@compound || Constants::IN_NOT_IN.include?(@arel_predicate))
|
|
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) }
|
|
end
|
|
|
|
end
|
|
end
|