Add a Rails controller from a gem
ruby, ruby-on-rails, ruby-on-rails-3, rubygems
Solution
Let's assume your gem is called MyGem and you have a controller called SamplesController that you want to use in the app. Your controller should be defined as:
module MyGem
class SamplesController < ApplicationController
def whatever
...
end
end
end
and in your gem directory it should live at app/controllers/my_gem/samples_controller.rb (not under the lib folder).
Then create engine.rb in your gems lib/my_gem folder with code
module MyGem
class Engine < Rails::Engine; end
end
You can write routes inside your gem by writing creating routes.rb in config folder with code
# my_gem/config/routes.rb
Rails.application.routes.draw do
match 'route' => 'my_gem/samples#index'
end
Final structure something like this
## DIRECTORY STRUCTURE
#
- my_gem/
- app/
- controllers/
- my_gem/
+ samples_controller.rb
- config/
+ routes.rb
- lib/
- my_gem.rb
- my_gem/
+ engine.rb
+ version.rb
+ my_gem.gemspec
+ Gemfile
+ Gemfile.lock
Thats it.
Problem
I am developing a rubygem specifically for Rails applications and I want to add a controller from my gem so that it will be available on the Rails app(Similar to what devise does with RegistrationsController, SessionsController). On the gem side: I've tried adding the following app/controllers/samples_controller.rb ``` class SamplesController < ApplicationController def index . . end end ``` And then on my rails routes add it either as: ``` match 'route' => 'samples#index' ``` or ``` resources :samples ``` Clearly I got something wrong over there but I have no idea what is it? Do I need to explicitly require my SampleController somewhere or an initializer on the app? Right now I am getting this error when accessing the route ``` uninitialized constant SamplesController ``` Thanks :)