[英]Ruby on Rails: Reference to a singleton class action in routes
我正在嘗試在 Rails 上使用 Ruby 在 class 上工作,以創建一個簡單的 controller。 從這個意義上說,我有一個 singleton,我需要參考它的路線。 這怎么可能?
我得到的信息:
找不到 Test::TestController 的操作“foo”
測試文件夾中的 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
路線文件:
Rails.application.routes.draw do
namespace 'test' do
resources :test
end
get '/:id', to: 'test/test#foo'
end
這是不可能的。 它甚至不是一個好主意。
Rails 控制器以請求和環境的形式接受輸入,其中包括服務器設置和中間件作為初始化程序 arguments 塞進的任何內容。 它們不是全局變量,例如 PHP。
controller 本身的動作實際上並沒有采取任何 arguments。 因此,即使您可以將您的操作聲明為 class 方法,您也絕對沒有上下文。 它實際上非常無關緊要,因為您必須更換整個路由器層才能調用它。
Ruby 甚至沒有真正的 singleton 類。 如果您想要一個無法實例化的 object,請使用模塊(不,您不能將模塊設為導軌中的 controller)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.