0

在我的大多数 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
4

1 回答 1

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
于 2013-05-29T11:36:56.307 回答