Reputation: 701
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
Upvotes: 0
Views: 217
Reputation: 101821
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).
Upvotes: 4