trnc
trnc

Reputation: 21577

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!

Upvotes: 22

Views: 27372

Answers (4)

Hanfu Liao
Hanfu Liao

Reputation: 95

Change this:

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

to:

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

Upvotes: 1

pangpang
pangpang

Reputation: 8821

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

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

Upvotes: 43

Frederick Cheung
Frederick Cheung

Reputation: 84114

Action Controller has an internal method called process that your method is masking. Pick a different name for your action.

Upvotes: 3

Milan Jaric
Milan Jaric

Reputation: 5646

You can call any (not just private) methods like this

class SomeClass

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

c=SomeClass.new

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

or

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

BTW, in your code, try to use

self.process_cc(...)

Upvotes: 3

Related Questions