我在routes块中定义了一个类来处理ajax的东西
#config/routes.rb Rails.application.routes.draw do class OnlyAjaxRequest def matches?(request) request.xhr? end end #rest of the routes end
不过,我在编辑器中得到这样的警告:
Do not define constants this way within a block.Lint/ConstantDefinitionInBlock(RuboCop)
这似乎是一个坏习惯,但我不知道我怎么能修复它,有什么想法吗?
从 docs :
如果要定义一次常量,请在块外定义它,如果在外部范围中定义常量会有问题,请使用变量或方法。
您可以定义 OnlyAjaxRequest 在块外初始化以修复问题。
OnlyAjaxRequest
class OnlyAjaxRequest def matches?(request) request.xhr? end end Rails.application.routes.draw do # ... end
constraints 选项。
constraints
is_ajax_request = ->(request) { request.xhr? } get '/some_route', to: 'test#action', constraints: is_ajax_request