0

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
Community
  • 1
  • 1
Yarin
  • 173,523
  • 149
  • 402
  • 512

1 Answers1

1

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

Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75