class ActiveRecord::DynamicMatchers::Method
Attributes
Public Class Methods
Source
# File lib/active_record/dynamic_matchers.rb, line 32 def match(model, name) klass = matchers.find { |k| k.pattern.match?(name) } klass.new(model, name) if klass end
Source
# File lib/active_record/dynamic_matchers.rb, line 52 def initialize(model, method_name) @model = model @name = method_name.to_s @attribute_names = @name.match(self.class.pattern)[1].split("_and_") @attribute_names.map! { |name| @model.attribute_aliases[name] || name } end
Source
# File lib/active_record/dynamic_matchers.rb, line 37 def pattern @pattern ||= /\A#{prefix}_([_a-zA-Z]\w*)#{suffix}\Z/ end
Source
# File lib/active_record/dynamic_matchers.rb, line 41 def prefix raise NotImplementedError end
Public Instance Methods
Source
# File lib/active_record/dynamic_matchers.rb, line 63 def define model.class_eval <<-CODE, __FILE__, __LINE__ + 1 def self.#{name}(#{signature}) #{body} end CODE end
Source
# File lib/active_record/dynamic_matchers.rb, line 59 def valid? attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) } end
Private Instance Methods
Source
# File lib/active_record/dynamic_matchers.rb, line 84 def attributes_hash "{" + attribute_names.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 72 def body "#{finder}(#{attributes_hash})" end
Source
# File lib/active_record/dynamic_matchers.rb, line 88 def finder raise NotImplementedError end
Source
# File lib/active_record/dynamic_matchers.rb, line 78 def signature attribute_names.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 ‘_`.