助手采用更实用的方法:
module ProductsHelper
def tiered_price(product, tier, quantity)
price = case tier
when 1 then product.price * 1.2
when 2 then product.price * 1.4
else product.price * 1.6
end
price * product.quantity
end
end
# view
<%= number_to_currency( tiered_price(@product, 1, 2) ) %>
但在我看来,这在模型中会更好:
class Product < ActiveRecord::Base
def tiered_price(tier, quantity)
price = case tier
when 1 then price * 1.2
when 2 then price * 1.4
else price * 1.6
end
price * quantity
end
end
# view
<%= number_to_currency(@product.tiered_price(1, 2)) %>
如果您真的希望能够像 find_by_name 一样编写 @product.tier_one_quanity_two,则需要挂钩 method_missing,它具有一些复杂性和速度开销,但会像这样:
class Product < ActiveRecord::Base
def method_missing(method, *args)
match = method.to_s.match(/tier_(.*)_quantity_(.*)/)
if match && match[0] && match[1]
unit_price = case match[0]
when 'one' then price * 1.2
when 'two' then price * 1.4
else price * 1.6
end
quantity = case match[1]
when 'one' then 1
when 'two' then 2
#.. and so on
end
unit_price * quantity
else
super
end
end
end