代码之家  ›  专栏  ›  技术社区  ›  Nilay Singh

如何从Rails控制器中删除代码块

  •  1
  • Nilay Singh  · 技术社区  · 6 年前

    我正试图从我的控制器中删除一个代码段,使它看起来干净而精简。在我的一个控制器中,我必须使用许多条件,这使得我的控制器看起来很重。我只想删除其他文件中的代码块,并将其包含到我的控制器中。 My controller code

    在这里你可以看到我使用了一些逻辑,比如:

       if search == 'Primary'
        if rain_fall_type == "Agriculture, Forestry and Fishing"
    
          if compare == "None"
            search = "None"
            rain_fall_type
          elsif compare == "All"
            rain_fall_type = compare
            data = [
              "Crops",
              "Livestock",
              "Forestry and Logging",
              "Fishing and Aquaculture",
            ]
          else
            search = "None"
            rain_fall_type = compare
          end
    
        elsif rain_fall_type == "None"
          rain_fall_type
    
          data = [
            "Primary",
          ]
    
        else
          data = [
            "Agriculture, Forestry and Fishing",
            "Mining and Quarrying",
          ]
        end
        ......
    

      a = if test == "a"
           #my code
        end
    
       #and in my controller 
    
      def test
         a 
      end
    

    我们可以在ruby中这样做吗?将所有代码块放在一个文件中,并在我的控制器中调用该值。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Mugur 'Bud' Chirica    6 年前

    为了给你一个简短的答案,你可以马上开始,你可以这样做:

    if search == 'Primary'
      data, search = RainFallSearcher.call(rain_fall_type, compare)
    end
    
    class RainFallSearcher
      def call(rain_fall_type, compare)
        if rain_fall_type == "Agriculture, Forestry and Fishing"
          if compare == "None"
            search = "None"
            rain_fall_type
          elsif compare == "All"
            rain_fall_type = compare
            data = [
              "Crops",
              "Livestock",
              "Forestry and Logging",
              "Fishing and Aquaculture",
            ]
          else
            search = "None"
            rain_fall_type = compare
          end
        elsif rain_fall_type == "None"
          data = [
            "Primary",
          ]
        else
          data = [
            "Agriculture, Forestry and Fishing",
            "Mining and Quarrying",
          ]
        end
    
        return data, search
      end
    end
    

    RainFallSearcher 在一个由Rails加载的位置(我会选择 app/services

    您不必将所有逻辑都放在控制器或模型中,实际上建议将它们精简,并创建简单(或复杂)的Ruby对象来处理逻辑。

    这篇文章很有解释性: https://www.engineyard.com/blog/keeping-your-rails-controllers-dry-with-services