1

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

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

但是方法是明确定义的。是什么赋予了?

4

1 回答 1

6

如果您的意思是类方法,那么

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
于 2013-04-10T14:03:36.283 回答