How(where) to define a method that to be called by views?

Hi,

I just dabbed Ruby on rails abit and what to know where is the right
place
to define a method, that prinf some output information to views, based
on
some variable.

I define a function "def foo " in contrioller but the calling from a
view
“test.rhtml” give errors. I google a while and did not find a quick
answer
for this. Or shall I do this in helper class?

May some one shed some light on this?

Thanks.

On 12/6/07, Sun [email protected] wrote:

May some one shed some light on this?
Yes that’s what helpers are for.

Also, the rails-talk list is a better place to ask questions about
rails.


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

On Dec 6, 9:02 am, “Sun” [email protected] wrote:

May some one shed some light on this?

Thanks.

You’ll need to post some code. It’s basically done like this:

app/controllers/my_controller.rb:
class MyController < ActiveController::Base
  def index
    @somevar = 'Hi!'
  end
end

app/views/my_controller/index.rhtml:
<p><%= @somevar %></p>

If you want to call a routine in your view, it’s best to put it into
the appropriate helper class (that’s what they are there for)

app/helpers/my_controller_helper.rb:
module MyControllerHelper
  def somevar
    'Hi!'
  end
end

now your controller/view looks like this

app/controllers/my_controller.rb:
class MyController < ActiveController::Base
  def index
  end
end

app/views/my_controller/index.rhtml:
<p><%= somevar %></p>

“Reacher” [email protected] wrote in message
news:[email protected]

answer
def index
app/helpers/my_controller_helper.rb:
def index
end
end

app/views/my_controller/index.rhtml:

<%= somevar %>

[/code]

thanks you guys for your prompt answers!!!, you are of great help. I am
in a
hurry to revise some rails code written by others and am a complete
newbie
to either rails or ruby, just borrowed one book and try to understand
the
ideas. .

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs