简体   繁体   English

Ruby on Rails:参考路线中的 singleton class 动作

[英]Ruby on Rails: Reference to a singleton class action in routes

I am trying to work over a class using Ruby on Rails in order to create a simple controller.我正在尝试在 Rails 上使用 Ruby 在 class 上工作,以创建一个简单的 controller。 In that sense, I have a singleton and I need to refer routes to it.从这个意义上说,我有一个 singleton,我需要参考它的路线。 How is it possible?这怎么可能?

The message I get:我得到的信息:

The action 'foo' could not be found for Test::TestController找不到 Test::TestController 的操作“foo”

The controller file, inside a Test folder:测试文件夹中的 controller 文件:

class Test::TestController < ApplicationController
    class << self
            def index
                    render json: {test:"Hello World!"}
            end
            def foo
                    render json: {response:"It works!"}
            end
    end
end

The routes file:路线文件:

Rails.application.routes.draw do
    namespace 'test' do
            resources :test
    end
    get '/:id', to: 'test/test#foo'
end

Its not possible.这是不可能的。 And its not even a remotely good idea.它甚至不是一个好主意。

Rails controllers take their input in form of the request and env which encompasses things like server settings and anything the middleware has stuffed away as initializer arguments. Rails 控制器以请求和环境的形式接受输入,其中包括服务器设置和中间件作为初始化程序 arguments 塞进的任何内容。 They are not globals like in for example PHP.它们不是全局变量,例如 PHP。

The actions of a controller themselves don't actually take any arguments. controller 本身的动作实际上并没有采取任何 arguments。 So even if you could declare your actions as class methods you would have absolutely no context.因此,即使您可以将您的操作声明为 class 方法,您也绝对没有上下文。 And its actually pretty damn irrelevant since you would have to replace the entire router layer to even get it called.它实际上非常无关紧要,因为您必须更换整个路由器层才能调用它。

Ruby does not even have real singleton classes either. Ruby 甚至没有真正的 singleton 类。 If you want an object that can't be instantiated use a module (and no you can't make a module a controller in rails).如果您想要一个无法实例化的 object,请使用模块(不,您不能将模块设为导轨中的 controller)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM