Only change layout on a certain condition

layout, ruby-on-rails

Solution

What you seem to be trying to do is always setting the layout, and if you don't want to change it, setting it to what it already was. Instead, because of the recursion, I think you should only set the layout if your condition holds.

before_filter set_baco_layout

def set_baco_layout
  self.class.layout "baco" if request.path_info.include?( '/baco/' )
end

It would be a cleaner design, however, if your engine controllers each called layout.

class Baco::BatsController < ApplicationController
  layout "baco"
  ...

That might not seem DRY, but it is a step cleaner.

To fix the DRY thing, I'd used inheritance. Have a base controller class which sets the layout and inherit your other controllers from your base.

class Baco::BaseController < ApplicaitonController
  layout "baco"
end

class Baco::BatsController < Baco::BaseContoller
  ...

Problem

In my gem I only want to change the layout on a certain condition. I know I can have a method for specifying the layout, but how can I point to the current layout in that method? I've learned that `_layout` points to the layout name, but it causes a stack overflow if it's called in the method that specifies the layout. Here's my code for clarification (In my engine's application controller): ``` layout :get_layout def get_layout current = _layout # this is what I want, but causes a stack overflow request.path_info.include?( '/baco/' ) ? 'baco' : current end ``` So for example: The application with this gem specifies a layout called 'qday', now the gem needs to change the layout if the path includes 'baco', but if it doesn't, it should render 'qday'. Thanks!

Original source