在Rails控制器中使用define_method会产生语法错误

时间:2012-10-22 16:32:18

标签: ruby-on-rails ruby

使用Rails 3.2。以下是我的控制器:

class ShopsController < ApplicationController
  ...

  class << self
    Shop::SHOP_TYPES.each do |shop_type|
      define_method "nearby_#{shop_type.pluralize}"
        @nearby_type = "#{shop_type.pluralize}"
      end
    end
  end

 ...
end

class Shop < ActiveRecord::Base  
  SHOP_TYPES =  %w(cafe restaurant)
end

但是,它最后syntax error, unexpected keyword_end, expecting $end end属于class ShopsController < ApplicationController。我试图保持代码干燥,以便我不必手动编码:

class ShopsController < ApplicationController
  ...

  def nearby_cafes
    @nearby_type = "cafes"
  end

  def nearby_restaurants
    @nearby_type = "restaurants"
  end

 ...
end

我做错了什么?感谢。

1 个答案:

答案 0 :(得分:5)

define_method需要阻止,您错过了do

所在行的define_method