Question

I am newbie in Rails but have quite an extensive amount of experience coding in other language (such as Java). Well, I liked Ruby's metaprogramming.

Usually, when in my way of learning Rails... I see some plug in such as public_activity, or others that can simply do

include Namespace::SomeModel

And that, in the case of public_activity, their SomeModel's method is somehow called on before the record is created. I suspect that before_create is included in SomeModel. So... I begin to experiment but was stuck that, obviously, the before_create become unavailable to the SomeModel class I am having that is located in directory manually auto-loaded on rails s.

What I want to ask if, how can just by including SomeModel, one of its method is called on ActiveRecord create event?

I just downloaded the source code of the code, but well... it will takes time. And, just to anticipate I cannot found the answer; you guys are my better teacher than silent code. So, give me time to answer even for slightest hint. Thanks.

Était-ce utile?

La solution

Rails allows to extend the class you're including a module in. Basic techniques are described in http://api.rubyonrails.org/classes/ActiveSupport/Concern.html#method-i-included

This allows to "set up" a module, like

module Foo
  extend ActiveSupport::Concern
  included do
    # Within this area "self" now refers to the class in which the module is included
    # Every method you now call is called agains the class

    # As such you can now write things like
    validates_inclusion_of ...
    define_method ...
  end
end

Autres conseils

It is a quite famous procedure

Module NewModule
  extend ActiveSupport::Concern

  def self.included(base)
    base.after_create :a_method
  end

  def a_method
    # your_code_here
  end
end

class A < ActiveRecord::Base
  include NewModule
end

with ActiveSupport::Extend you give NewModule's class and instance methods to A accordingly.

The NewModule.included code is executed when NewModule is included to another class.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top