당신이 사용하고자하는 코드는 다양한 메소드 호출에 걸쳐 매우 비슷합니다 특히, method_missing
를 사용하여 특히 좋아입니다.
class ActiveRecord::Base
def method_missing(meth, *args, &block)
if meth.to_s =~ /^find_by_(.+)$/
run_find_by_method($1, *args, &block)
else
super # You *must* call super if you don't handle the
# method, otherwise you'll mess up Ruby's method
# lookup.
end
end
def run_find_by_method(attrs, *args, &block)
# Make an array of attribute names
attrs = attrs.split('_and_')
# #transpose will zip the two arrays together like so:
# [[:a, :b, :c], [1, 2, 3]].transpose
# # => [[:a, 1], [:b, 2], [:c, 3]]
attrs_with_args = [attrs, args].transpose
# Hash[] will take the passed associative array and turn it
# into a hash like so:
# Hash[[[:a, 2], [:b, 4]]] # => { :a => 2, :b => 4 }
conditions = Hash[attrs_with_args]
# #where and #all are new AREL goodness that will find all
# records matching our conditions
where(conditions).all
end
end
define_method
작동하는 것처럼도 보이는 : 누군가가 method_missing이 boo
에, boo
으로 인수라고, x.boo
및 boo
이 존재하지 않는 호출 (선택 사항) 블록마다 - 여기이 site의 예입니다 당신을 위해, 그러나 나는 그것에 관한 경험이 method_missing
보다 적습니다. 동일한 링크의 예는 다음과 같습니다.
%w(user email food).each do |meth|
define_method(meth) { @data[meth.to_sym] }
end
감사합니다. 나는'method_missing'으로 선험적으로 알지 못하는 메소드가 될 것입니다. –