Forum: Ruby on Rails Define methods for controllers, helper AND models?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Joshua M. (Guest)
on 2006-03-27 22:47
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. :-)
Joshua
Josh S. (Guest)
on 2006-03-27 23:03
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
Anonymous (Guest)
on 2006-04-07 10:41
(Received via mailing list)
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
This topic is locked and can not be replied to.