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

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

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

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


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