【问题标题】:Refactoring Model Methods in Ruby On Rails在 Ruby On Rails 中重构模型方法
【发布时间】:2010-10-17 05:51:45
【问题描述】:
我的阵营在rails中使用的一个常用成语如下:
def right_things(all_things, value)
things = []
for thing in all_things
things << thing if thing.attribute == value
end
return things
end
我怎样才能使它更好/更快/更强?
谢谢
-C
【问题讨论】:
标签:
ruby-on-rails
ruby
refactoring
methods
【解决方案1】:
def right_things(all_things, value)
all_things.select{|x| x.attribute == value}
end
【解决方案2】:
如果您的东西是 ActiveRecord 模型,并且您只需要为当前目的选择的项目,如果您使用的是 Rails 2.0(?肯定是 2.1)或更高版本,您可能会发现 named_scopes 很有用。
class Thing
named_scope :rightness, lambda { |value| :conditions => ['attribute = ?', value] }
end
所以你可以说
Thing.rightness(123)
,(在这种情况下)类似于
Thing.find_by_attribute(123)
因为它归结为 SQL 查询,但修改 SQL 更容易链接。如果这对你有用,当然可能没用......