CodeSmith
CodeSmith

Reputation: 2233

How to make a Rails engine expose a file to the Rails App Root?

I know inside my Rails engine I can create an app/controllers/blah_controller.rb file and that controller will be accessible from my Rails app just like it was defined in the Rails app itself.

If I want the engine to expose a file into the root of the Rails application, where do I put that in the Rails engine? A basic gem would have a structure like:

my_engine
  |_bin
  |_lib
  .gitignore
  my_engine.gempspec
  Gemfile
  Rakefile
  README.md 

Do I just add the_file.rb to root of the gem? If so, how does Rails know to include it and not the other files in the gem root?

my_engine
  |_bin
  |_lib
  .gitignore
  my_engine.gempspec
  Gemfile
  Rakefile
  README.md 
  the_file.rb    # I want this file to be present in the Rails app root.

Upvotes: 1

Views: 1213

Answers (1)

Dan Myasnikov
Dan Myasnikov

Reputation: 158

No Rails won't know how to load root path files.

The part of rails you are looking for is a railtie engine: http://api.rubyonrails.org/classes/Rails/Engine.html

I hope you mounted the engine to an application so you can debug. Within your app that has an engine, you can check eager loaded paths:

MyEngine::Engine.config.eager_load_paths

which returns an array of all loaded paths.

All you need to do is: to configure Engine to load the root path:

module MyEngine
  class Engine < ::Rails::Engine
    isolate_namespace MyEngine
    config.eager_load_paths << File.expand_path('../../..', __FILE__)
  end
end

Then create a dummy initializer in the Rails app, that requires your engine root file:

# /config/initializers/my_engine_dummy.rb
require 'your_engine_root_file.rb'

Place some methods inside your_engine_root_file.rb

p 'Welcome to my engine`

load rails console from your rails application and see the beautiful message

Assumption:

I assumed that you are using MyEngine as the namespace for the engine.

Suggestion:

Not to do that :) As many know that name collapse is a common thing in software development. So you might want to isolate your engine files behind the namespace.

Hope that helps

Upvotes: 1

Related Questions