Yarin
Yarin

Reputation: 183499

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

Upvotes: 0

Views: 74

Answers (1)

Ismael
Ismael

Reputation: 16720

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

Upvotes: 1

Related Questions