Ruby on rails 从gem添加Rails控制器
我正在开发专门用于Rails应用程序的rubygem,我想从我的gem中添加一个控制器,以便它可以在Rails应用程序上使用(类似于RegistrationController、SessionController的功能) 在宝石方面: 我尝试添加以下内容 app/controllers/samples\u controller.rbRuby on rails 从gem添加Rails控制器,ruby-on-rails,ruby,ruby-on-rails-3,rubygems,Ruby On Rails,Ruby,Ruby On Rails 3,Rubygems,我正在开发专门用于Rails应用程序的rubygem,我想从我的gem中添加一个控制器,以便它可以在Rails应用程序上使用(类似于RegistrationController、SessionController的功能) 在宝石方面: 我尝试添加以下内容 app/controllers/samples\u controller.rb class SamplesController < ApplicationController def index . . end e
class SamplesController < ApplicationController
def index
.
.
end
end
module Samples
class SamplesController < ApplicationController
def index
.
.
end
end
end
或
很明显我有点不对劲,但我不知道是什么?我是否需要在某个地方明确要求我的SampleController或应用程序上的初始值设定项
现在我在访问路由时遇到此错误
uninitialized constant SamplesController
谢谢:)首先,您的代码中有一个输入错误:
appingcontroller
应该是ApplicationController
然后,您没有遵循Rails命名约定(资源等的复数形式):
- 在您的路线中,它必须是
或resources:samples
resource:sample
- 您的控制器类应为
和类SamplesController
- 控制器的文件名应为
samples\u controller.rb
遵循约定,您应该会很好。要设置路由,请在项目的config目录中创建routes.rb文件。要使其与示例管线匹配,请执行以下操作: config/routes.rb
Rails.application.routes.draw do
<resource definition here>
end
你看过这个网站了吗
假设您的gem名为MyGem,并且您有一个名为SamplesController的控制器,希望在应用程序中使用该控制器。您的控制器应定义为:
module MyGem
class SamplesController < ApplicationController
def whatever
...
end
end
end
最终结构是这样的
## 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
就是这样。谢谢,但是我仍然得到了
未初始化的常量SamplesController
你能仔细检查一下你的文件是否命名正确(samples\u controller.rb),定义了正确的类(class SamplesController要求'my_gem/engine'
添加到lib/my_gem.rb
中/lib/my_gem/engine.rb
的目的是什么?
include 'samples'
module MyGem
class SamplesController < ApplicationController
def whatever
...
end
end
end
module MyGem
class Engine < Rails::Engine; end
end
# my_gem/config/routes.rb
Rails.application.routes.draw do
match 'route' => 'my_gem/samples#index'
end
## 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