Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put model "utility" functions in Ruby on Rails

I have a rails app with several models.

I have a function that I want to access from several models.

What's the best place to put this code and how can I make it accessible from the models that need to get at it?

My understanding is that helpers are just for views. Is this correct?

It seems wrong to create a plug-in and put it in the vendor folder - this is my code and integral to my app. Is this correct?

Thanks.

like image 529
Phil McT Avatar asked Aug 07 '09 01:08

Phil McT


2 Answers

The simplest solution would be to create a module under lib and mix this into the models that need it, for instance, in lib/fooable.rb:

module Fooable
  def do_foo
  end
end

And then in your various models:

class MyModel < ActiveRecord::Base
  include Fooable
end

No need to require fooable.rb, the Rails autoloading mechanism will find it for you as long as it's named using correct conventions.

like image 179
Luke Redpath Avatar answered Nov 06 '22 07:11

Luke Redpath


In order to lessen the repetition of code, you could also create a main class which would include that module and the simply inherit from it from every model you'd like to share the behaviour.

Something like:

module Fooable
  def do_foo
  end
end

class ParentModel < ActiveRecord::Base
  include Fooable
end

class Product < ParentModel end
class User < ParentModel end
class Item < ActiveRecord::Base end

Thus, in that example, both Product and User would share the do_foo functionality and Item would not.

like image 36
Alessandra Pereyra Avatar answered Nov 06 '22 06:11

Alessandra Pereyra