代码之家  ›  专栏  ›  技术社区  ›  svelandiag

在块中不要这样定义常量。在块中定义类时

  •  0
  • svelandiag  · 技术社区  · 4 年前

    我在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)
    

    这似乎是一个坏习惯,但我不知道我怎么能修复它,有什么想法吗?

    1 回复  |  直到 4 年前
        1
  •  2
  •   Arun Kumar Mohan    4 年前

    docs :

    如果要定义一次常量,请在块外定义它,如果在外部范围中定义常量会有问题,请使用变量或方法。

    您可以定义 OnlyAjaxRequest 在块外初始化以修复问题。

    class OnlyAjaxRequest
      def matches?(request)
        request.xhr?
      end
    end
    
    Rails.application.routes.draw do
      # ...
    end
    

    constraints 选项。

    is_ajax_request = ->(request) { request.xhr? }
    
    get '/some_route', to: 'test#action', constraints: is_ajax_request
    
    推荐文章