Yarin
Yarin

Reputation: 183539

Using Rack gem in Rails

I'm trying to use a stupid little Rack gem I just wrote in my Rails project, but I keep on getting an uninitialized constant error whenever I call it. This is driving me insane because I've already written Rack gems before, and those work in my Rails projects just fine.

In my Gemfile:

gem 'hide_heroku', :git => 'https://github.com/ykessler/hide-heroku'

In my application.rb:

module Tester
  class Application < Rails::Application

    config.middleware.use Rack::HideHeroku

But starting my local server, I get:

uninitialized constant Rack::HideHeroku (NameError)

The gem:

module Rack

  class HideHeroku

    def initialize(app)
      @app=app
    end

    def call(env)
      @status, @headers, @response = @app.call(env)
      @request = Rack::Request.new(env)
      [@status, _apply_headers, @response]
    end

    private

      def _apply_headers
        if /\.herokuapp\.com\/?.*/ =~ @request.url
          @headers['X-Robots-Tag'] = 'noindex, nofollow'
        end
        @headers
      end

  end

end

See it here: https://github.com/ykessler/hide-heroku

Upvotes: 1

Views: 315

Answers (1)

Chris Heald
Chris Heald

Reputation: 62648

The issue here is probably the project's structure. You need to have a lib/hide_heroku.rb file in your gem, which bootstraps the gem, or you need to specify the require path on your gem line, like so:

gem 'hide_heroku', :git => 'https://github.com/ykessler/hide-heroku', :require => "rack/hide_heroku"

(Or you can just require 'rack/hide_heroku' in your app).

Bundler will try to require the gem's name when you call Bundler.setup, but if you aren't using that file structure, it can't find your files to include.

Upvotes: 2

Related Questions