Last active
December 15, 2015 22:48
-
-
Save amolpujari/5335115 to your computer and use it in GitHub Desktop.
Different ways of having modular active record models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
end | |
end | |
end | |
# 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 | |
end | |
# Approach #2 Let User include module | |
# app/models/user/module_name.rb | |
module ModuleName | |
def blah_blah_blah | |
end # and so on .... | |
end | |
# 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 | |
end | |
def ensure_something_type | |
self.something_type ||= SomethingType.find_by_name("something something") | |
end | |
end | |
# app/models/user.rb | |
concerned_with :validations, | |
:data_uploader, | |
:ensure_something_type, | |
:jingo_filters, | |
:macro_reports, | |
:pricing, | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment