2012-09-01 48 views
2

我有两个方法,这样在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 

我想,当我从过程调用process_cc,它创建的文档,并重定向到doc_path之后。也许我期待行为,哪些铁轨无法处理,但处理方法不会调用process_cc方法,并尝试渲染模板,而不是...

对此有什么建议?

谢谢!

+4

是你的问题仍然存在,当你删除'private'关键字?我问,因为我不认为你的问题是关联的方法是私人的。 – Robin

+0

如果你的方法'process_cc'没有被调用,可能它被子类中的另一个方法'process_cc'重写。 – Baldrick

回答

-1

你可以这样调用

class SomeClass 

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

c=SomeClass.new 

c.method("some_method").call("James Bond") 

c.instance_eval {some_method("James Bond")} 

BTW任何(不只是私人的)方法,在你的代码,尝试使用

self.process_cc(...) 
+0

如果你看看OP代码,这实际上不会有效果。如果一个方法在同一个类中调用私有方法,那么由于没有明确的接收方,该方法是否是私有方法并不重要。另外,为什么只要使用'send(“some_method”)''方法转换为proc? –

3

动作控制器具有一种称为process的内部方法,表示您的方法是屏蔽的。为您的动作选择一个不同的名称。

5

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

obj.send(:method_name [, args...]) 
0

更改此:

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 

到:

def process_cc(type) 
    @doc = Document.new(:type => type) 
    if @doc.save 
    redirect_to doc_path(@doc) and return 
    else 
    redirect_to root_path, :notice => "Error" and return 
    end 
end