Can I define a "before_save" callback in a module?

Is it possible to define a before_save in a module? So 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 

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

Sorry if this is something simple - I'm new to Ruby and Rails.

+48
ruby ruby-on-rails
Sep 16 '11 at 12:16
source share
2 answers

In Ruby on Rails <3 (no 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 the Rails Concern function)

 module MyModule extend ActiveSupport::Concern included do before_save :do_something end def do_something #do whatever end end 
+92
Sep 16 '11 at 12:28
source share
+3
Sep 16 '11 at 12:25
source share



All Articles