【问题标题】:How do I limit the accessing of a method across an app?如何限制跨应用程序访问方法?
【发布时间】:2009-11-23 16:46:24
【问题描述】:

所以我有一种方法和相应的部分,可以在我们网站某些区域的侧边栏中包含一组随机照片。

现在我在 ApplicationController 中有一个 random_photos 方法,并设置了 before_filter

从某种意义上说,它使 random_photos 方法的内容在我需要的任何地方都可用,但是当我也不知道时(即,当我不知道时)它也不必要地执行一些复杂的 SQL 查询需要访问那些随机照片)。

那么,我如何才能将random_photos 方法的访问限制为仅在我真正需要 时才访问?

【问题讨论】:

    标签: ruby-on-rails methods


    【解决方案1】:

    您可以在 before_filter 调用中添加 :if 条件,如下所示:

    class ApplicationController < ActiveController::Base
      before_filter :random_photos, :if => is_it_the_right_time?
    

    【讨论】:

      【解决方案2】:

      另一个选择是使用skip_before_filter。这仅取决于您想要不同的控制器数量。如果您只想成为例外的少数控制器,请使用skip_before_filter。如果有许多控制器要绕过过滤器,请使用其他建议之一。

      class ApplicationController < ActiveController::Base
         before_filter :random_photos
      
         def random_photos
           @photos = Photo.random
         end
      end
      
      class OtherController < ApplicationController
        skip_before_filter :random_photos
        ...
      end
      

      【讨论】:

        【解决方案3】:

        您可以将random_photos 方法保留在ApplicationController 中,并将before_filters 放在您的其他控制器中。

        class ApplicationController < ActiveController::Base
          ...
          def random_photos
            @photos = Photo.random
          end
        end
        
        class OtherController < ApplicationController
          before_filter :random_photos, :only => 'show'
          ...
        end
        

        【讨论】:

          【解决方案4】:

          这取决于有多少函数在使用random_photos...

          如果少数,则使用 vrish88 的方法,但使用 after_filter

          class ApplicationController < ActiveController::Base
            after_filter :random_photos, :if => is_it_the_right_time?
            ...
            private
          
            def is_it_the_right_time?
              return @get_random_photos
            end
          end
          
          class SomeController < ApplicationController
          
            def show
              @get_random_photos = true
              ...
            end
          end
          

          如果控制器中的每个功能都将使用它,则使用skip_before_filter 或将before_filter 在控制器中移出应用程序控制器。

          完成它的方法很多,没有一种比下一个更正确。尽量让它尽可能简单和透明,这样您就不会在几个月后重新创建功能,因为您忘记了所有部件的位置。

          【讨论】:

            猜你喜欢
            • 2012-11-02
            • 2012-11-19
            • 2015-10-04
            • 1970-01-01
            • 1970-01-01
            • 2016-07-18
            • 1970-01-01
            • 2012-01-19
            相关资源
            最近更新 更多