RubyFanatic
RubyFanatic

Reputation: 2281

Modularize an ActiveRecord class

If I have classes like this,

class A < ActiveRecord::Base
  include ExampleModule
end

class B < ActiveRecord::Base
  include ExampleModule
end

module ExampleModule
  module ClassMethods
    ...
  end      

  def included(base)
    ...
  end
end

how do I get the a reference to class A or B inside of ExampleModule upon referencing including this module into either one of those classes? I'm asking this question because I wanted to do something like adding has_one :association or after_create :do_something to class A or B via including ExampleModule such as below.

class A < ActiveRecord::Base
  include ExampleModule
end

class B < ActiveRecord::Base
  include ExampleModule
end

module ExampleModule
  has_one :association
  after_create :do_something      

  module ClassMethods
    ...
  end      

  def included(base)
    ...
  end
end

Is there a better way to do this as well? Thanks!

Upvotes: 0

Views: 438

Answers (2)

Dty
Dty

Reputation: 12273

If what you're wanting to do is call has_one or after_create depending on which class is including the module you can do this

module Extender
  def self.included(base)
    if base.name == A.name
       # do stuff for A
       has_one :association
    elsif base.name == B.name
       # do stuff for B
       after_create :do_something
    end
  end
end

Upvotes: 1

rjz
rjz

Reputation: 16510

If you extend ActiveSupport::Concern, you should be able to do it when the module is included:

module ExampleModule

  extend ActiveSupport::Concern

  def do_something
    # ...
  end

  included do
    has_one :association
    after_create :do_something      
  end
end

Upvotes: 1

Related Questions