Is it possible to define a 'before_save' callback in a module?

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


Is it possible to define a before_save callback in a module? Such that with a class like this:

class Model
  include MongoMapper::Document
  include MyModule
end

and a module like this:

module MyModule
  before_save :do_something

  def do_something
    #do whatever
  end  
end 

do_something will be called before any Model objects are saved? I've tried it like this but get undefined method 'before_save' for MyModule:Module.

Apologies if it's something simple - I'm new to Ruby and to Rails.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

In Ruby on Rails < 3 (without Rails features, only Ruby)

module MyModule
  def self.included(base)
    base.class_eval do
      before_save :do_something
    end
  end

  def do_something
    #do whatever
  end
end

In Ruby on Rails >= 3 (with Rails Concern feature)

module MyModule
  extend ActiveSupport::Concern

  included do
    before_save :do_something
  end

  def do_something
    #do whatever
  end
end

Solution 2 - Ruby on-Rails

A module's included method might be what you need.

http://www.ruby-doc.org/core-2.1.2/Module.html#method-i-included

Solution 3 - Ruby on-Rails

You can do this with ActiveSupport::Concern(actually and without it, but it more clear and preferred)

require 'active_support/concern'

module MyModule
  extend ActiveSupport::Concern

  included do
    # relations, callbacks, validations, scopes and others...
  end

  # instance methods

  module ClassMethods
    # class methods
  end
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRussellView Question on Stackoverflow
Solution 1 - Ruby on-RailsSimone CarlettiView Answer on Stackoverflow
Solution 2 - Ruby on-RailsjimwormView Answer on Stackoverflow
Solution 3 - Ruby on-Railsuser1136228View Answer on Stackoverflow