未定义的方法错误,但方法在Ruby中定义...为什么?

时间:2013-04-10 14:02:01

标签: ruby-on-rails ruby

我无法在我写的渲染器类上调用任何方法。它的方法是否应该暴露?

class EntriesController < ApplicationController
  def show
    BaseRenderer.renderer_for(@entry) # @entry is loaded with a before_filter
  end
end

# app/renderers/base_renderer.rb
class BaseRenderer
  def renderer_for(entry)
    klass ||= "#{entry.entry_type}Renderer".constantize
    klass.new(entry)
  end
end

我得到NoMethodError at ... undefined method 'renderer_for' for BaseRenderer:Class

但该方法已明确定义。是什么给了什么?

1 个答案:

答案 0 :(得分:4)

如果你的意思是一个类方法,那么

def renderer_for(entry)

应该是

def self.renderer_for(entry)

class BaseRenderer
  class << self
    def renderer_for(entry)
      # could also change to this
      Object.const_get("#{entry.entry_type}Renderer").new(entry)
    end
  end
end