问题
I'm trying to contribute to an open source project and I need a controller to handle a couple of forms that need to be submitted in.
I created these controllers inside a directory inside the gem called app/controllers/gemname/my_controller.rb
.
However, when I try to access the controller, it seems not to be loaded (I get a name error just as if I typed something like NonExistentController).
How do I load my controller with the gem?
Thanks!
回答1:
Let's assume your gem is called MyGem
and you have a controller called SuperController
that you want to use in the app. Your controller should be defined as:
module MyGem
class SuperController < ApplicationController
def whatever
...
end
end
end
and in your gem directory it should live at app/controllers/my_gem/super_controller.rb
(not under the lib
folder). Check out the source for Devise as they do the same thing.
[Edit] You may learn something from A Guide To Starting Your Own Rails Engine Gem regarding your current project.
回答2:
The guide in Brandon's answer is very helpful but only applies to rails 3.0. Since 3.1 you can create a plugin. Like this: rails plugin new my_engine --mountable
See this helpful guide:
http://namick.tumblr.com/post/17663752365/how-to-create-a-gemified-plugin-with-rails-3-2-rspec
(> Rails 3.0)
Rails official guide (edge):
http://edgeguides.rubyonrails.org/engines.html
http://edgeguides.rubyonrails.org/plugins.html
Old enginex:
https://github.com/josevalim/enginex
(3.0 only)
来源:https://stackoverflow.com/questions/8689142/how-to-include-a-controller-with-a-ruby-on-rails-gem