Reputation: 2139
I am developing a rails app and I want all my objects to have a certain method that process them. Now, while I realize that I could write that method in each object's model, I would rather stick with the DRY (don't repeat yourself) theory and place the method in one place.
Is there a place I could place a method where all my objects have access to?
Upvotes: 0
Views: 35
Reputation: 914
Ruby and rails offer a number of options depending on what object you want to have access to a method.
ChiuBaka's answer is one option, however rails in particular offers a number of more readable options.
If you are looking for something on the controller/view level. You can simply place it in the app/helpers/application_helper.rb
file. If you want to limit access you can create controller specific helper files in the same directory.
If you are looking at models. You can simply create a base model that inherits from activerecord::base
, implement your method there, and then have your models inherit from that.
class MyBase < ActiveModel::Base
def myinstancemethod
end
def myclassmethod
end
end
then
class MyModel < MyBase
end
then you can call like so
instance = MyModel.new
instance.myinstancemethod
or
MyModel.myclassmethod
Upvotes: 3
Reputation: 789
Place the code you want in all of your models in a module in your /lib folder and require it in your models.
Upvotes: 0