Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active March 7, 2017 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisleech/9348597f13ebee348e258a67fe80fac5 to your computer and use it in GitHub Desktop.
Save krisleech/9348597f13ebee348e258a67fe80fac5 to your computer and use it in GitHub Desktop.
Sharing Rails config between apps by inheriting from Rails::Application

Instead of inheritence we can use a mixin, since this is Rails a concern will do nicely.

module Other
  module RailsConfig
    extend ActiveSupport::Concern

    included do
      config...
    end
  end
end

module MyApp
  class Application < Rails::Application
    include Other::RailsConfig
  end
end

Usually we have this:

module MyApp
  class Application < Rails::Application
    config...
  end
end

But we want this:

# this would be in a seperate gem
module Other
  class Application < Rails::Application
    config...
  end
end

module MyApp
  class Application < Other::Application
  end
end

module MyOtherApp
  class Application < Other::Application
  end
end

However because Rails sets Rails.application when Rails::Application is first inherited from it means that Rails.application becomes an instance of Other::Application, not MyApp::Application. This in turn means routes do not get loaded correctly, since they are MyApp::Application.routes.draw and thus Rails.application.routes is empty and no routes work.

The relevant Rails source is:

railties/lib/rails/application.rb

def inherited(base)
  super
  Rails.app_class = base
  add_lib_to_load_path!(find_root(base.called_from))
end

and

railties/lib/rails.rb

def application
  @application ||= (app_class.instance if app_class)
end

The fix is this:

module MyApp
  class Application < Other::Application
  end
end

Rails.application = MyApp::Application.instance

Is this a good idea, who knows?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment