Where to put common methods

I seem to have missed something in my (limited) rails experience.

I can put lots of stuff in helpers for the views to call but these
methods aren’t accessible to the controller.

Now they always bang on about “Dont Repeat Yourself” but I have to
repeat some methods that I need in the controller as well. Surely this
is not “A Good Thing”?

Am I doing something wrong?

G.

In you controller, just add

helper :sample

I like to jam common pieces into modules in the lib directory.

Does anyone know if it is it considered good practice to mix controller
and view functionality in the helper files. I see the helper :sample
like sishen pointed out in plugins and core code, but I have also heard
from others that one should only put modules for use with views in the
helper directory.

giorgio wrote:

I seem to have missed something in my (limited) rails experience.

I can put lots of stuff in helpers for the views to call but these
methods aren’t accessible to the controller.

Now they always bang on about “Dont Repeat Yourself” but I have to
repeat some methods that I need in the controller as well. Surely this
is not “A Good Thing”?

Am I doing something wrong?

G.

I’m afraid I still dont get it…

I can put a method in application_helper.rb
I can then put helper:application in the controller

I still cant call that method from the controller.

How do you call it?

G.

Hello Giorgio,

If you have a method that you would like to access both from your
views and from your controllers, put it into ‘application.rb’, and
mark it as a helper method using the method “helper_method”. For
example, if you had a method called ‘my_helpful_method’ in
application.rb, just add the line ‘helper_method :my_helpful_method’
above it, like this:

 # in the file application.rb
 helper_method :my_helpful_method
 def my_helpful_method
     "I do something very useful!"
 end

Now you can access my_helpful_method both from controllers and from
views.

I hope that helps,

-Seth

Components are for sharing common controller/view.

Sometimes there is no sure way of where to put your code, and for
that. application.rb and helper it. I personally, break up a lot of
my codes into plugins and lib files.

Zach I.
→ Blog – http://www.zachinglis.com
→ Company – http://www.lt3media.com
→ Portfolio – http://portfolio.zachinglis.com

Hey Giorgio,
I agree with you

I am having a problem in that variables that get set in the method are
available to controllers but not the views. The method gets invoked
from the view but its variables are not being received in the view.
For example if I have a @my_helpful_var = ‘xyz’ then in the view I
can’t get the value of @my_helpful_var in my view .rhtmls. I can get
to it in my controllers
How do I get around this?

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