开发者

Metaprogramming for finder method

Let's pretend I have some items in Stuff table. The names are: RedBaloon, SmallBall, BigShoe, ShoeString

I want to use metaprogramming to create find_by_name methods for me.

The issue that I'm having is that I want to using the following as the names for the methods: red_baloon, small_ball, big_shoe开发者_开发技巧, shoestring

NB: "shoestring" is not a typo.

Here's some code that I started with for you to respond to:

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


Like @apneadiving said in their comment, you case use the special String#underscore method. Here is how I would clean up your code:

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

I don't know if there are any other problems because I could not find good documentation on validates_inclusion_of, but I think this fixes your problem.

Also, in the future, you don't need to interpolate a string into an identical string ("#{string} is string) and, because both strings and symbols are valid names in these methods, you don't need to perform a conversion. Even then, use #to_string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜