will initialize break the layout settings in rails? will initialize break the layout settings in rails? ruby-on-rails ruby-on-rails

will initialize break the layout settings in rails?


initialize is used internally to Rails to, well, initialize a new instance of your controller so it can then serve requests on it. By defining this method in this particular manner, you are breaking Rails.

There is a way through! A light at the end of the tunnel. A pot of gold at the end of the rainbow:

def initialize  @title = "Admins"  superend

See that little super call there? That'll call the superclass's initialize method, doing exactly what Rails would do otherwise. Now that we've covered how to do it your way, let's cover how to do it the "officially sanctioned" Rails way:

class AdminsController < ApplicationController  before_filter :set_title  # your actions go here  private          def set_title      @title = "Title"    endend

Yes, it's a little more code but it'll result in less frustration by others who gaze upon your code. This is the conventional way of doing it and I strongly encourage following conventions rather than doing "magic".

EDIT: If you're using Rails 5 then you'll need to use before_action instead of before_filter.


I'm not sure exactly how layout works its magic, but I'm willing to bet it's in a yield block in the ActionController#initialize method. So your overriding of initialize would explain the problem.

Looks like you have too options here:

  1. Close out your new definition with super to call the ActionController initialize which should use the layout defined in the class.

    eg:

    def initialize  @Title = "Admins"  superend
  2. Use a before filter to initialize your variables. This is the Rails Way of initializing values in a controller

    class AdminsController < ApplicationController  layout "layout_admins"  before_filter :set_title  def set_title    @Title = "Admins"  end  def index    ....... some code here  endend