Define methods for controllers, helper AND models?


#1

Hi all

I know that I can define methods in e.g. the application controller and
make them available to the helpers using helper_method(), but how can I
make them available in the models?

I have for example the following method, that I want to be able to call
from any model I wish…

def ApplicationController
helper_method :member

def member
session[:member]
end
end

Thanks for any help. :slight_smile:
Joshua


#2

Joshua M. wrote:

I know that I can define methods in e.g. the application controller and
make them available to the helpers using helper_method(), but how can I
make them available in the models?

You can’t, or at least not without hacking it. If you are following the
MVC design pattern, your model shouldn’t know anything about the view or
controller. This allows you to use a model in other environments, such
as from a cron activated script. You want your business logic in the
model, and application logic in the controller/view.

So you can’t get to the controller object from the model. But if you
have an algorithm you want to use in both places, you can put it in a
library module and include it in both places.

–josh
removed_email_address@domain.invalid


#3

I’m not sure, but you could try the following

put

module Member
def member
session[:member]
end
end

in a member_modules.rb file in \lib

then in the model

require “member_modules”

class MyModel < ActiveRecord::Base

include Member

end

or perhaps even better in app\controllers\application.rb

class ActiveRecord::Base

include Member

end

You should give it a try…

Saludos

Sas

PS: I’m pretty new to ruby, I’m sure there may be a better way