dealing with concerns

Taking care of concerns, my views are

They are meant not to have large/GOD classes

They are not specific to ActiveRecord

They are there to help us out find out dependencies easier

They should not be dependent on each other, if module A has concern :b, then there should exist paths “root/a.rb” and “/root/a/b.rb“. Though this we ourself have to make sure about concerns path by writing additional code at initialization

I always willing to write clean and neat code, and have end up maintaining my concerns the following ways

  1. Reopening Class
  2. Include Module
  3. Extend ActiveSupport::Concern

I do have one doubt though, out of 3 approaches, which one is good for faster execution?

# config/initializers/concerns.rb
class << ActiveRecord::Base
def concerned_with(*concerns)
concerns.each do |concern|
require_dependency "#{name.underscore}/#{concern}"
klass = concern.to_s.classify.constantize rescue nil
send(:include, klass) if klass.is_a? Module
# Approach #1 opening User class
# app/models/user/validations.rb
class User << ActiveRecord::Base
validates :mobile, :length => { :in => 6..20 }, :allow_blank => true, :allow_nil => true
validates_presence_of :country, :name
before_create :is_zip_validated_by_yahoo?
# and so on
# Approach #2 Let User include module
# app/models/user/module_name.rb
module ModuleName
def blah_blah_blah
end # and so on ….
# Approach #3 extend ActiveSupport::Concern
# app/models/user/ensure_something_type.rb
module EnsureSomethingType
extend ActiveSupport::Concern
included do
before_create :ensure_something_type
belongs_to :something_type
has_one :something_base_type, :through => :something_type
def ensure_something_type
self.something_type ||= SomethingType.find_by_name("something something")
# app/models/user.rb
  concerned_with  :validations,

view raw


hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s