简体   繁体   中英

Creating gem that works with or without Rails

What's the convention for building a gem that works within or without Rails environments?

For example, I just created the hide_heroku gem, which is essentially a piece of Rack middleware. I then added in a Railtie class so that it would load execute automatically in a Rails environment, but now if I turned around and tried to include it in a Nesta app for example, I'll get an error that it can't load rails...

In this answer https://stackoverflow.com/a/2072169/165673 @SimoneCarletti alludes to something in this vein:

if you package a plugin as Gem you can reuse it in non-Rails projects and provide Rails-specific initializations using the init.rb file. Non-Rails applications will simply ignore it.

But it's an old answer and im not sure what he's talking about. What's the best way to do this?

hide_heroku.rb:

require "rack/hide_heroku"
require "hide_heroku/railtie"

module HideHeroku
end

hide_heroku/railtie.rb:

require "rails"

module HideHeroku
  class Railtie < ::Rails::Railtie

    config.before_configuration do
      Rails.application.config.middleware.use Rack::HideHeroku  
    end

  end
end

I never done this but I've seen something like this on other similar cases

require "hide_heroku/railtie" if Object.const_defined?(Rails) 

So this will only require your railtie if Rails is defined

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