Refactoring ActiveRecord models with a base class versus a base module
There's a fundamental difference between those two methods that all the other answers are missing, and that's rails' implementation of STIs (Single Table Inheritance):
http://api.rubyonrails.org/classes/ActiveRecord/Base.html (Find the "Single Table Inheritance" section)
Basically, if you refactor your Base class like this:
class Base < ActiveRecord::Base
def foo
puts "foo"
end
end
class A < Base
end
class B < Base
end
Then, you are supposed to have a database table called "bases", with a column called "type", which should have a value of "A" or "B". The columns on this table will be the same across all your models, and if you have a column that belongs to only one of the models, your "bases" table will be denormalized.
Whereas, if you refactor your Base class like this:
Module Base
def foo
puts "foo"
end
end
class A < ActiveRecord::Base
include Base
end
class B < ActiveRecord::Base
include Base
end
Then there will be no table "bases". Instead, there will be a table "as" and a table "bs". If they have the same attributes, the columns will have to be duplicated across both tables, but if there are differences, they won't be denomarlized.
So, if one is preferable over the other, yes, but that's specific to your application. As a rule of thumb, if they have the exact same properties or a big overlap, use STI (1st example), else, use Modules (2nd example).
How do I create a base class that abstracts a has and belongs to many relationship in Rails 4.1
Look into a concept called concerns, introduced in Rails 4. Abstracting a class inherited from ActiveRecord::Base is a recipe for trouble.
A good explanation How to use concerns in Rails 4.
How to refactor shared methods?
One popular approach is to use ActiveSupport concerns. You would then place the common logic typically under app/concerns/
or app/models/concerns/
directory (based on your preference). An illustrative example:
# app/concerns/mooable.rb
module Mooable
extend ActiveSupport::Concern
included do
before_create :say_moo
self.mooables
where(can_moo: true)
end
end
private
def say_moo
puts "Moo!"
end
end
And in the model:
# app/models/cow.rb
class Cow < ActiveRecord::Base
include Mooable
end
In order to make it work this way you have to add the following line to config/application.rb
config.autoload_paths += %W(#{config.root}/app/concerns)
More information:
- http://chris-schmitz.com/extending-activemodel-via-activesupportconcern/
- http://blog.waxman.me/extending-your-models-in-rails-3
- http://api.rubyonrails.org/classes/ActiveSupport/Concern.html
Whats a good ruby idiom for breaking up a large class into modules?
Breaking a class into modules, while tempting (because it's so easy in Ruby), is rarely the right answer. I usually regard the temptation to break out modules as the code's way of telling me it wants to be split into more tightly-focussed classes. A class that's so big you want to break it into multiple files is pretty much guaranteed to be violating the Single Responsibility Principle.
EDIT: To elaborate a bit on why breaking code into modules is a bad idea: it's confusing to the reader/maintainer. A class should represent a single tightly-focussed concept. It's bad enough when you have to scroll hundreds of lines to find the definition of an instance method used at the other end of a long class file. It's even worse when you come across an instance method call and have to go looking in another file for it.
Is that a proper way to refactor ActiveRecord fat models?
Like someone told me a long time ago:
Code refactoring is not a matter of randomly moving code around.
In your example that is exactly what you are doing: moving code into another file
Why is it bad?
By moving code around like this, you are making your original class more complicated since the logic is randomly split into several other classes. Of course it looks better, less code in one file is visually better but that's all.
Prefer composition to inheritance. Using mixins like this is asking to "cleaning" a messy room by dumping the clutter into six separate junk drawers and slamming them shut. Sure, it looks cleaner at the surface, but the junk drawers actually make it harder to identify and implement the decompositions and extractions necessary to clarify the domain model.
What should I do then?
You should ask yourself:
- Which code goes together and could be part of a new class / module ?
- Where does it makes sense to extract code to somewhere else ?
- Do I have some piece of code that is shared across my application ?
- Can I extract recurrent patterns in my code base ?
Extract Service Object
I reach for Service Objects when an action meets one or more of these criteria:
- The action is complex
- The action reaches across multiple models
- The action interacts with an external service
- The action is not a core concern of the underlying model
- There are multiple ways of performing the action
Extract Form Objects
When multiple model can be updated by a a single form submission, you might want to create a Form Object.
This enable to put all the form logic (name conventions, validations and so on) into one place.
Extract Query Objects
You should extract complex SQL/NoSQL queries into their own class. Each Query Object is responsible for returning a result set based on the criterias / business rules.
Extract Presenters / Decorators
Extract views logic into presenters. Your model should not deal with specific views logic. Moreover, it will enable you to use your presenter in multiple views.
More on decorators
Thanks to this blog post to help me putting these together.
How to refactor shared methods?
One popular approach is to use ActiveSupport concerns. You would then place the common logic typically under app/concerns/
or app/models/concerns/
directory (based on your preference). An illustrative example:
# app/concerns/mooable.rb
module Mooable
extend ActiveSupport::Concern
included do
before_create :say_moo
self.mooables
where(can_moo: true)
end
end
private
def say_moo
puts "Moo!"
end
end
And in the model:
# app/models/cow.rb
class Cow < ActiveRecord::Base
include Mooable
end
In order to make it work this way you have to add the following line to config/application.rb
config.autoload_paths += %W(#{config.root}/app/concerns)
More information:
- http://chris-schmitz.com/extending-activemodel-via-activesupportconcern/
- http://blog.waxman.me/extending-your-models-in-rails-3
- http://api.rubyonrails.org/classes/ActiveSupport/Concern.html
Factoring out belongs_to into a common module
When to create a module and when to use inheritance?
A question came up today that got me thinking about how much Ruby on Rails developers really understand about the tools they use.
The question related to refactoring two models that shared functionality. A common enough requirement and a very sensible thing to want to do but the comments and solutions raised my eyebrows some what.
This was the question, somewhat edited and reformatted to make it clearer
I'm factoring out the meat of an ActiveRecord class A into a module M,
so that I'm able to duplicate certain data pipelines.The original A model had ActiveRecord macro methods such as belongs_to
:X.Although I'm able to separate out non-AR things fine into the module
and mix it back into A, the module does not know anything about
belongs_to or anything about AR model B out of the box.How do I make those available to the module, and then mix it back into
the new shallow A, which only includes M now, and B, which is a clone
of A with its own underlying AR table? Or should I write something
like an acts_as plugin (right?) instead of M? Retaining belongs_to in
A and duplicating it in B works, but defeats the DRY principle
What I didn't understand was why the person asking the question was putting this code into a module instead of into a class that the models could descend from.
In Rails (almost) every class descends from another class right?
You see code like
class MyModel < ActiveRecord::Base
all over the place. Fine that ::Base might seem a little mysterious and I can see how that kind of hides what is going on here so lets look at the controller example
All controllers descend from ApplicationController when first generated right?
So you get
class MyController < ApplicationController
How many of you put code into the application controller like before filters and current)user methods and end up using that code in your controllers and views?
Once you take time to think about it a bit then you can see that if you put code in ApplicationController that is public or protected then all controllers that descend from ApplicationController get that functionality right?
ApplicationController is just a class that descends from ActionController::Base the definition looks like this
class ApplicationController < ActionController::Base
Now that looks so familiar the above usage is so common that I start to think that a lot of Rails developers struggle to see the wood for the trees.
This is all about inheritance.
Rails puts a bunch of methods into the ActionController::Base
and ActiveRecord::Base
classes (That's all they are, classes inside a module) so you can descend your own classes from these classes thereby inheriting the methods and functionality provided by these base classes.
So why not create an abstract ActiveRecord::Base class to solve the problem. This seemed to me the most totally obvious and natural approach to take.
I came up with this solution
In a_base_class.rb
class ABaseClass < ActiveRecord::Base
abstract true
has_many :whatevers
belongs_to :whatevers
def common_methods
#some code here
end
end
Then class a
class A < ABaseClass
# Whatever
end
This could be placed inside a module for namespacing purposes
If you want to put that in a module then descend from WhateverModule::ABaseClass then that's a cool way of name spacing the new base class so that class names don't conflict and that is one of the main purposes of using a module. To name space classes.
Obviously use whatever real class names that make sense to you.
@Rishav Rastogi provided a great answer for using modules and this is what got mne really wondering why thwe solution was not so clear to others and why the question had even been asked in the first place and I started to get the impression that people don't really know what code like this really does
class SomeController < ApplicationController
and
class MyModel < ActiveRecord::Base
When this is stuff that Rails developers use every day?
It's all about inheritance.
Abstract and non abstract classes all inherit from a single class right? The class being inherited from may well inherit from a number of other classes forming a single inheritance chain but it's still single inheritance. each class only descends from one other class.
So what can modules do to help?
Modules are somewhat confusingly used for 2 purposes.
1) To name space things as already mentioned
2) To provide a multiple inheritance scenario. Multiple inheritance is a dirty word in the development world. Things can end up in a right mess but modules provide quite a neat solution.
An example of why you would want multiple inheritance
ActiveRecord::Base provides methods like find_by_something and find.all that return an array of ActiveRecord::Base objects (classes are the code objects are actual things)
Knowing this it would make sense to have the Base class inherit from the array class, but if it did that then it wouldn't be able to inherit from any other more appropriate class. The solution is to mix in a module. If the module contains the array class you get all the juice of array functionality such as .each and .empty? plus all the juice of the other classes that ActiveRecord::Base uses.
So when to use a module and when to inheritance?
Use a module for name spacing (classes can live inside a module)
Use a class for inheritance
So use them both together at the same time unless you want multiple inheritance in which case just use modules
How can I refactor a Rails Controller action to eliminate clutter?
You should move the code out to your model and let your model deal with 1) the parameter being nil
and 2) using ActiveRecord to query the database effectively.
In your controller, have lines like this for each of your variables:
@friends = @user.friends.updated_since(params[:last_updated])
(I've renamed @buddies
here to @friends
, because we want to maintain consistency in naming the things of the system)
Then, in your Friend
model, define a class method called updated_since
that does that logic:
class Friend < ActiveRecord::Base
def self.updated_since(last_updated)
if last_updated.present?
where("updated_at > ?", last_updated)
else
all
end
end
end
Related Topics
Add_Foreign_Key VS Add_Reference in Rails
Rspec: How to Write a Test That Expects Certain Output But Doesn't Care About the Method
How to Return Correct Http Error Codes from Ruby on Rails Application
Best Way to Handle Data Attributes in Slim
Discriminate First and Last Element in Each
In Ruby What Is the Meaning of Colon After Identifier in a Hash
Examples of 'Things' That Are Not Objects in Ruby
How to Detect User Agent in Rails 3.1
How to Do a Left Outer Join Using Rails Activerecord
Built in Way to List Directories in a Directory in Ruby
Ruby on Rails 4 - What Authentication Gem to Use
Ruby on Rails Uncapitalize First Letter
How to Install a Gem Globally Without Sudo Using Rbenv