Rubytastic
Rubytastic

Reputation: 15491

how to dry up 2 almost identical methods that are used in almost every controller?

In most of my rails controllers I use 2 methods to set layout and sub_layout Feels messy, lot of repeat == not dry ( methods in almost every controller).

Im looking for some constructive suggestions on how to dry this code

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

Upvotes: 0

Views: 173

Answers (1)

apneadiving
apneadiving

Reputation: 115511

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

In your controller:

layout :resolve_layout

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

Upvotes: 2

Related Questions