Helpers in Rails

B

Bob Aman

Ok, so, I have a method that I need to use in several models and two
controllers. I don't want to duplicate code, and initially, rail's
concept of a helper seemed like a good fit, but it looks like maybe it
only works with controllers, so maybe not. I'm a pretty much a nuby,
but I think maybe I want to do a mixin? If so, where would the module
with my method go within the rails application folder structure? And
how do I do a mixin?
 
P

Pete Maley

I have run into the same problem. I'll give you two ways (that I can
think of) to implement this. There may be better ways, but I used the
first option.

OPTION #1

Create a new model.
app/models/common_model.rb
class CommonModel < ActiveRecord::Base
# class method you want to share
def self.some_method
# do something
end

# instance method you want to share
def some_other_method
# do something
end
end

Then you can have all of your other models inherit from CommonModel

app/models/existing_model.rb
require_dependency 'common_model'
class ExistingModel < CommonModel
# model specific code goes here
end

OPTION #2
Another alternative would be to use mixins as you suggested, possibly
like this.

app/models/common_methods.rb
module CommonMethods
def some_method
end
end

app/models/existing_model.rb
require_dependency 'common_methods'
class ExistingModel < ActiveRecord::Base
# mixin the module to get instance methods
include CommonMethods
end

Either of these implementations would make the common methods accessible
to your models, and therefore accessible to any controllers that can
access those models.

Hope this helps,
Pete
 
B

Bob Aman

A module's methods can be added to a class using SomeClass.extend. For example

What if I have both class and instance methods in my module?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top