在rails中调用私有方法?

Tro*_*nic 5 ruby-on-rails

我有两种这样的方法

def process
  @type = params[:type]
  process_cc(@type)
end

private

def process_cc(type)
  @doc = Document.new(:type => type)
  if @doc.save
    redirect_to doc_path(@doc)
  else
    redirect_to root_path, :notice => "Error"
  end
end
Run Code Online (Sandbox Code Playgroud)

我想,当我从进程调用process_cc时,它会创建Document并在之后重定向到doc_path.也许我期待导轨无法处理的行为,但是进程方法不会调用process_cc方法并尝试渲染模板而是...

有什么建议吗?

谢谢!

pan*_*ang 16

Object#send 使您可以访问对象的所有方法(甚至是受保护的和私有的).

obj.send(:method_name [, args...])
Run Code Online (Sandbox Code Playgroud)


Mil*_*ric 3

您可以像这样调用任何(不仅仅是私有)方法

class SomeClass

  private
  def some_method(arg1)
    puts "hello from private, #{arg1}"
  end
end

c=SomeClass.new

c.method("some_method").call("James Bond")
Run Code Online (Sandbox Code Playgroud)

或者

c.instance_eval {some_method("James Bond")}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,在您的代码中,尝试使用

self.process_cc(...)
Run Code Online (Sandbox Code Playgroud)