不要在块中以这种方式定义常量。在块中定义 class 时
Do not define constants this way within a block. When defining class within a block
我正在路由块中定义一个 class 来处理 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:
Do not define constants within a block, since the block’s scope does not isolate or namespace the constant in any way.
If you are trying to define that constant once, define it outside of the block instead, or use a variable or method if defining the constant in the outer scope would be problematic.
您可以在块外定义 OnlyAjaxRequest
class 来解决问题。
class OnlyAjaxRequest
def matches?(request)
request.xhr?
end
end
Rails.application.routes.draw do
# ...
end
由于约束非常简单,您甚至不需要创建 class。您可以将 lambda 传递给 constraints
选项。
is_ajax_request = ->(request) { request.xhr? }
get '/some_route', to: 'test#action', constraints: is_ajax_request
我不明白你为什么要在你的具体案例中的块内定义一个 class,因为你可以同样很好地定义它,但万一你遇到了你真的想在本地做,你可以做
Object.const_set(
"OnlyAjayRequest",
Class.new {
def matches?(request)
request.xhr?
end
}
)
我正在路由块中定义一个 class 来处理 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:
Do not define constants within a block, since the block’s scope does not isolate or namespace the constant in any way.
If you are trying to define that constant once, define it outside of the block instead, or use a variable or method if defining the constant in the outer scope would be problematic.
您可以在块外定义 OnlyAjaxRequest
class 来解决问题。
class OnlyAjaxRequest
def matches?(request)
request.xhr?
end
end
Rails.application.routes.draw do
# ...
end
由于约束非常简单,您甚至不需要创建 class。您可以将 lambda 传递给 constraints
选项。
is_ajax_request = ->(request) { request.xhr? }
get '/some_route', to: 'test#action', constraints: is_ajax_request
我不明白你为什么要在你的具体案例中的块内定义一个 class,因为你可以同样很好地定义它,但万一你遇到了你真的想在本地做,你可以做
Object.const_set(
"OnlyAjayRequest",
Class.new {
def matches?(request)
request.xhr?
end
}
)