简体   繁体   中英

How do I make a Rails 3 initializer module into a gem

Just trying to learn some basics of creating a gem. Right now I've created an initializer that looks like...

# config/initializers/fun_logger.rb
module FunLogger
  def fun_before_filter
    logger.info("\n\n\nGOT IT!\n\n\n")
  end
end

ActionController::Base.send(:include, FunLogger)

This allows me to add the following to my ApplicationController and it prints out GOT IT! in the log

before_filter :fun_before_filter 

So a few things I'm trying to figure out.

So to create a gem out of this...

  1. I believe I should be setting up this before_filter some other way, but not sure how to do that.
  2. I believe this initializer should be moved to the lib directory and auto-loaded somehow with the rails app.

Are these beliefs correct and if so how do I go about this?

You want to check out Railties . That'll get your gem running an initializer, or any of the other Rails-specific things you might want to accomplish.

As for making a before filter... that's generally not the best solution, and it's hard to tell from the sample exactly what you're trying to accomplish. A more customary way for gems to add behavior into the request/response cycle is by adding a Rack middleware , which leaves the user's controllers alone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM