UPDATE: I added a blog post based on this answer, but with much more detailed information: http://thoughtsincomputation.com/posts/coding-an-acts_as-gem-for-rails-3
-
I donβt know another source of the textbook from my head, but here are some general tips.
Rails 3 uses the really useful Railtie feature - see http://api.rubyonrails.org/classes/Rails/Railtie.html .
So, if I implemented act_as_ * gem, I would start there. My railtie might look something like this:
# lib/acts_as_awesome/railtie.rb require 'rails' require 'acts_as_awesome' module ActsAsAwesome class Railtie < Rails::Railtie config.to_prepare do ApplicationController.send(:extend, ActsAsAwesome::Hook) end end end
and ActsAsAwesome :: Hook code:
# lib/acts_as_awesome/hook.rb module ActsAsAwesome::Hook def acts_as_awesome(*args) options = args.extract_options!
I feel that the concepts here sound and have used similar processes before. Basically, Rails had to execute the to_prepare block once during production and before every request in development (we want because the ApplicationController will be reloaded at this time, potentially destroying our hook method); and the hook is simple: it adds a binding to all controllers (more precisely, to all controllers that extend the ApplicationController) to allow the user to enter real βAwesomeβ code into their controllers, without affecting other controllers that he does not need.
The hook #acts_as_awesome alone does not pass the Awesome function. This is because not all controllers may need this feature. Instead, the method is responsible for introducing the real amazing stuff through the ActsAsAwesome :: InstanceMethods module. This way, the user only gets the Awesome function if they explicitly call the act_as_awesome method. He also adds in front of the filter in front of the filter to demonstrate that the code in this method will be evaluated exactly as if it were in the target class of the controller.
This method should work the exact same way if you target models instead of controllers: just insert your hook into ActiveRecord :: Base. Since AR: B only loads when Rails loads, you can probably include it in the initializer (see Railtie Docs), but I reserve the right to make mistakes here.
Railtie information retrieved: The documentation reads as if it were automatically detected, but I often have problems with this. To get around this, just ask for railtie from the main gem source file (in the example above it would be lib / actions_as_awesome.rb).
You can see the entire ActsAsAwesome source in all its glory of my github account: http://github.com/sinisterchipmunk/acts_as_awesome
Hope this is helpful. Your question was somewhat high, so a high level answer is the best I can do.
-Colin MacKenzie IV
http://thoughtsincomputation.com
@sinisterchipmnk