class ActiveRecord::DynamicMatchers::Method
Public Class Methods
Source
# File lib/active_record/dynamic_matchers.rb, line 38 def define(model, name) model.class_eval <<-CODE, __FILE__, __LINE__ + 1 def self.#{name}(#{signature(model, name)}) #{body(model, name)} end CODE end
Source
# File lib/active_record/dynamic_matchers.rb, line 30 def match(name) FindBy.match?(name) || FindByBang.match?(name) end
Source
# File lib/active_record/dynamic_matchers.rb, line 34 def valid?(model, name) attribute_names(model, name.to_s).all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) } end
Private Class Methods
Source
# File lib/active_record/dynamic_matchers.rb, line 51 def attribute_names(model, name) attribute_names = name.match(pattern)[1].split("_and_") attribute_names.map! { |name| model.attribute_aliases[name] || name } end
Source
# File lib/active_record/dynamic_matchers.rb, line 68 def attributes_hash(model, method_name) "{" + attribute_names(model, method_name).map { |name| ":#{name} => _#{name}" }.join(",") + "}" end
Given that the parameters starts with ‘_`, the finder needs to use the same parameter name.
Source
# File lib/active_record/dynamic_matchers.rb, line 56 def body(model, method_name) "#{finder}(#{attributes_hash(model, method_name)})" end
Source
# File lib/active_record/dynamic_matchers.rb, line 47 def make_pattern(prefix, suffix) /\A#{prefix}_([_a-zA-Z]\w*)#{suffix}\Z/ end
Source
# File lib/active_record/dynamic_matchers.rb, line 62 def signature(model, method_name) attribute_names(model, method_name.to_s).map { |name| "_#{name}" }.join(", ") end
The parameters in the signature may have reserved Ruby words, in order to prevent errors, we start each param name with ‘_`.