ActiveSupport::Concern
Instead of defining an included
method to handle extending a class, we can
extend ActiveSupport::Concern
.
It is actually a pretty simple but powerful concept. It has to do with code reuse as in the example below. Basically, the idea is to extract common and/or context specific chunks of code in order to clean up the models and avoid them getting too fat and messy.
Example
When we want to share code between classes in Ruby, we create a module.
module UsefulCode
def self.included(base)
base.extend ClassMethods
base.class_eval do
scope :disabled, -> { where(disabled: true) }
end
end
module ClassMethods
...
end
end
ActiveSupport::Concern
gives us a way to simplify the extraction of shared code.
require 'active_support/concern'
module UsefulCode
extend ActiveSupport::Concern
included do
scope :disabled, -> { where(disabled: true) }
end
class_methods do
...
end
end
Resources
- Put chubby models on a diet with concerns
- SoftDelete - Ruby Gem that uses a concern to share code.