简体   繁体   中英

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. In that sense, I have a singleton and I need to refer routes to it. How is it possible?

The message I get:

The action 'foo' could not be found for Test::TestController

The controller file, inside a Test folder:

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. They are not globals like in for example PHP.

The actions of a controller themselves don't actually take any arguments. So even if you could declare your actions as class methods you would have absolutely no context. 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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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