Where should I put a method in Rails that will be used by all of my models?
-
3Duplicate? http://stackoverflow.com/questions/2328984/rails-extending-activerecordbase – Pablo Marambio Feb 07 '12 at 04:56
4 Answers
You can write reusable methods in a module and include in necessary models.
create a file in lib/reusable.rb
module Reusable
def reusable_method_1
puts "reusable"
end
def reusable_method_2
puts "reusable"
end
end
Lets say if you want to use this in user model
class User < ActiveRecord::Base
include Reusable
end
And also ensure that the autoload_path enabled for lib/ directory in application.rb
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)

- 6,658
- 6
- 29
- 47
-
I saw a lot of answers to this question and none of them mentioned including lib in autoload_paths. +1 for that! solved my problem – Uri Klar Dec 08 '13 at 12:57
Active record extensions while server starts
# config/initializers/core_extensions.rb
class ActiveRecord::Base
# write ur common base code here
def self.per_page
@@per_page ||= 10
end
def self.pagination(options)
paginate :per_page => options[:per_page] || per_page, :page => options[:page]
end
end

- 7,583
- 4
- 37
- 48
There are multiple ways in which you could do achieve this
- Use OOP and and create a sub class for ActiveRecord::Base in your project and use that class as a parent for all your models
- Monkey path ActiveRecord::Base
- Create a module and include that in all your models

- 1,509
- 9
- 12
You'll want to do some research on a Rails convention called "Concerns". Here's the lowdown: Create sub-directory called concerns in your app directory. Create your module in app/concerns and include the module in all of your models. Add the path to app/concerns to your config.autoload_path in config/application.rb.
Before you do any of that, I'm curious as to what sort of method would need to be included in ALL models? How many models are we talking and what problem are you trying to solve?

- 3,389
- 1
- 16
- 14
-
It's for data to a remote server, namely a socket.io server. I'm using socket.io for realtime updates and I need to send those updates from multiple models. – JRPete Feb 07 '12 at 06:13
-
Agreed, Aroop. I think the solution needs to be at a higher level. I'm not familiar enough with socket.io, though. – Tom L Feb 07 '12 at 12:47