Rails 4 - Name Of Current Layout?

For me in Rails 6 the current_layout method would look like this

def current_layout
  self.controller.send :_layout, self.lookup_context, []
end

I believe the array is a list of formats used. The method _layout is build dynamically and I'm not sure what it's expecting in the formats parameter, but I got my desired behaviour with just an empty array Hope this helps.


In Rails 5, the code is:

controller.send :_layout, ["some_string_here"]

I don't know why it needs a string in the array but that's what got it working for me. Our helper file looks as follows:

def current_layout
  layout = controller.send :_layout, ["test"]
  return layout.inspect.split("/").last.gsub(/.haml/,"")
end

You can add the following helper method in ApplicationHelper:

def current_layout
     (controller.send :_layout).inspect.split("/").last.gsub(/.html.erb/,"") 
end

And you can call it accordingly in set_meta_tags method. Something like,

  def set_meta_tags
    title = (current_layout != "application") ? "#{current_layout} ::" : false
    set_meta title: "#{layout} #{setting(:site, :title)}", description: setting(:site, :description)
  end

NOTE:

.inspect gives me the layout name with its relative path.

.split("/").last will remove the relative path and returns just the layout name(with extension).

.gsub(/.html.erb/) removes the extension part of layout. You may need to adjust the extension based on the template engine you are using e.g. In case of Haml use .html.haml.


My Solution

From a chat with Kirti, it seems that my forgetting to mention we had manually set out layout was a big deal. This will work if you manually set your layout:

#app/helpers/application_helper.rb
def current_layout
   self.send :_layout
end

def set_meta_tags
    title  = (current_layout != "application") ? "#{current_layout.titleize} :: " : ""
    set_meta title: title + setting(:site, :title), description: setting(:site, :description)
end