Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling private methods in rails?

i have two methods like this

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

i want, that when i call process_cc from process, it creates the Document and redirect to the doc_path afterwards. maybe i'm expecting behaviour, which rails can't handle, but the process method doesn't call the process_cc method and tries to render a template instead...

any advice on this?

thanks!

like image 716
trnc Avatar asked Sep 01 '12 15:09

trnc


People also ask

How can we call private methods in Ruby?

Understanding Private Methods in Ruby You can only use a private method by itself. It's the same method, but you have to call it like this. Private methods are always called within the context of self .

What are private methods in Rails?

If a method is private, it may be called only within the context of the calling object---it is never possible to access another object instance's private methods directly, even if the object is of the same class as the caller. For protected methods, they are accessible from objects of the same class (or children).

How do you call private methods outside the class in Ruby?

It has to be explicitly included on each inherited class, or else the included method will only get called for the parent A . The class_eval block executes within the including class's context, so it's just like opening up the class in your class definition.


1 Answers

Object#send gives you access to all methods of a object (even protected and private).

obj.send(:method_name [, args...])
like image 102
pangpang Avatar answered Oct 20 '22 07:10

pangpang