14

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 :)

4

3 回答 3

22

假设您的 gem 名为 MyGem,并且您有一个名为 SamplesController 的控制器,您想在应用程序中使用它。您的控制器应定义为:

module MyGem
  class SamplesController < ApplicationController
    def whatever
      ...
    end
  end
end

并且在您的 gem 目录中,它应该位于 app/controllers/my_gem/samples_controller.rb (不在 lib 文件夹下)。

然后使用代码在您的 gems lib/my_gem 文件夹中创建 engine.rb

module MyGem
  class Engine < Rails::Engine; end
end

您可以通过在 config 文件夹中使用代码编写创建 routes.rb 来在 gem 中编写路由

# 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

而已。

于 2013-12-11T13:56:41.227 回答
0

要设置您的路线,请在项目的 config 目录中创建一个 routes.rb 文件。要使其与示例路由匹配,请执行以下操作:config/routes.rb

Rails.application.routes.draw do
  <resource definition here>
end

应用程序/控制器/samples_controller.rb

module Samples
  class SamplesController < ApplicationController
    def index
      .
      .
    end
  end
end

请记住将模块包含在应用程序控制器中

include 'samples'

你看过这个网站吗:

http://coding.smashingmagazine.com/2011/06/23/a-guide-to-starting-your-own-rails-engine-gem/

于 2012-06-02T23:00:46.000 回答
0

首先,您的代码中有一个错字:AppicationController应该是ApplicationController.

然后,您没有遵循 Rails 命名约定(资源等的复数形式):

  • 在您的路线中,它必须是resources :samplesresource :sample
  • 你的控制器类应该是class SamplesController
  • 控制器的文件名应该是samples_controller.rb.

遵守约定,你应该没问题。

于 2012-06-02T11:37:31.963 回答