如何干掉几乎每个控制器中使用的两种几乎相同的方法?

时间:2013-05-29 11:26:53

标签: ruby-on-rails ruby-on-rails-3 refactoring dry

在我的大多数rails控制器中,我使用2种方法来设置布局和sub_layout 感觉很乱,很多重复==不干(几乎每个控制器都有方法)。

我正在寻找关于如何干燥此代码的一些建设性建议

Profile_controller.rb:

class ProfilesController < ApplicationController

  before_filter :authenticate_user!
  layout        :resolve_layout

    def resolve_layout
        case action_name
          when "show"
            if user_signed_in?
              "application"
            else
              "application"
            end
          when "get_info"
            "modal"
          else
            "application"
        end
      end

      def sub_layout
        case params[:action]
          when "index"
            if user_signed_in?
              "left"
            else
              "right"
            end
          when "show"
            if user_signed_in?
              "left"
            else
              "right"
            end
          else
            "left"
        end
      end

      ..etc

1 个答案:

答案 0 :(得分:2)

class LayoutHandler < Struct.new(:action, :user_signed_in)

  def resolve
    case action
    when "get_info" then "modal"
    else "application"
    end
  end

  def sub
    case action
    when "index", "show" then user_signed_in? ? "left" :"right"
    else "left"
    end
  end
end

在您的控制器中:

layout :resolve_layout

def resolve_layout
  LayoutHandler.new(params[:action], user_signed_in?).resolve
end