让我们假设我在Stuff表中有一些项目。名称为: RedBaloon、SmallBall、BigShoe、ShoeString
我想使用元编程为我创建find_by_name方法。
我遇到的问题是,我希望使用以下内容作为方法的名称: red_baloon、small_ball、big_shoe、shoestring
注:"shoestring“不是打字错误。
下面是我开始的一些代码,供您响应:
class Stuff < ActiveRecord::Base
NAMES = ['RedBaloon', 'SmallBall', 'BigShoe', 'ShoeString']
validates_inclusion_of :name, :in => NAMES
class << self
NAMES.each do |n|
define_method "#{n}" do
find_by_kind(n)
end
end
end
end发布于 2011-03-23 08:32:15
就像@apneadiving在他们的评论中所说的,你可以使用特殊的String#underscore方法。下面是我如何清理你的代码:
class Stuff < ActiveRecord::Base
NAMES = ['RedBaloon', 'SmallBall', 'BigShoe', 'Shoestring']
validates_inclusion_of :name, :in => NAMES
class << self
NAMES.each do |name|
define_method name.underscore do
find_by_kind name
end
end
end
end我不知道是否还有其他问题,因为我找不到关于validates_inclusion_of的好文档,但我认为这解决了您的问题。
此外,将来不需要将字符串插入到相同的字符串中("#{string}为string),并且因为字符串和符号在这些方法中都是有效名称,所以不需要执行转换。即使到那时,也要使用#to_string。
https://stackoverflow.com/questions/4788318
复制相似问题