QUICK QUESTION: Method in Controller AND Helper

Hey,

Is there a way to write a method in the application controller and also
have it available as a helper method without rewriting it in the
application helper?

I’m pretty sure there is, but haven’t found the specifics on how to do
this yet.

Joe

I use this all the time;

def current_user
@current_user ||= session[:user] ? User.find_by_id(session[:user]) :
nil
end
helper_method :current_user

Gokhan
www.sylow.net

Joe P. wrote:

Hey,

Is there a way to write a method in the application controller and also
have it available as a helper method without rewriting it in the
application helper?

I’m pretty sure there is, but haven’t found the specifics on how to do
this yet.

Joe

def current_user
@current_user ||= session[:user] ? User.find_by_id(session[:user]) :
nil
end
helper_method :current_user
Thanks, now THAT’S what I’m talking about.

Is it possible to have method(s) in application_helper.rb available
for controllers, just like for views?
Actually my method is current_user too :smiley: and looks pretty similar,
but I’d like it in application_helper.rb…

James Schementi schrieb:

def method_to_use_in_controller
gets included into both the helper and controller.

Hi James,

instead of mixin in a whole helper module I’d declare the Helper method
as module_function like:

module SomeHelper
1000.times do |index|
define_method(:“waste_#{index}”) { index ** 2 }
end
def some_method(*some_args)
some_args.inspect
end

module_function :some_method
end

In your controller you can then do:

class Somes < ApplicationController
def some_action
SomeHelper.some_method
end
end

Don’t pollute your controller… :wink:

Regards
Florian

oh wow.
“module_function”

i’ve seen it, but never paid any attention.
thanks,

I always end up declaring them as self.blah

will use this, deffo.

Florian Aßmann wrote:

instead of mixin in a whole helper module I’d declare the Helper method
as module_function like:

module SomeHelper
1000.times do |index|
define_method(:“waste_#{index}”) { index ** 2 }
end
def some_method(*some_args)
some_args.inspect
end

module_function :some_method
end

ahoge wrote:

Is it possible to have method(s) in application_helper.rb available
for controllers, just like for views?
Actually my method is current_user too :smiley: and looks pretty similar,
but I’d like it in application_helper.rb…

define the method in your helper, then include your helper at the top of
the controller:

class ApplicationHelper
def method_to_use_in_controller

end
end

class ApplicationController
include ApplicationHelper
end

that’s the easiest way to do it … but if you have a lot of methods in
your ApplicationHelper you may want to pull it out into a module that
gets included into both the helper and controller.

Thanks