Reputation: 3692
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 :)
Upvotes: 16
Views: 5710
Reputation: 730
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.
Upvotes: 25
Reputation: 3919
to set up your route, create a routes.rb file in the config directory of your project. To have it match on the sample route, do the following: config/routes.rb
Rails.application.routes.draw do
<resource definition here>
end
app/controllers/samples_controller.rb
module Samples
class SamplesController < ApplicationController
def index
.
.
end
end
end
Remember to include the module in the application controller
include 'samples'
Have you looked at this site:
http://coding.smashingmagazine.com/2011/06/23/a-guide-to-starting-your-own-rails-engine-gem/
Upvotes: 0
Reputation: 33626
First of all you have a typo in your code: AppicationController
should be ApplicationController
.
Then, you're not following the Rails naming conventions (plural for resources etc.):
resources :samples
or resource :sample
.class SamplesController
andsamples_controller.rb
.Follow the conventions and you should be fine.
Upvotes: 0