Specifying a layout file for devise gem in rails (what does this do?)
I know how to specify a layout file for devise. But what I don't understand is how this works. Specifically, in the code below my layout_name_for_devise
is used if it's a devise controller. So then I figured 开发者_如何学编程this must mean the "application" layout would be used if it's NOT a devise controller (which in my case is in app/views/layouts/application.html.haml
). Now, I have other layouts, for example one called home
. I thought my views using my home
layout would break...but it turns out it work fine. I don't understand how this works. For example, when the code below runs, how is it that my app/views/layouts/home.html.haml
layout still gets called correctly?
class ApplicationController < ActionController::Base
layout :layout_by_resource
protected
def layout_by_resource
if devise_controller?
"layout_name_for_devise"
else
"application"
end
end
A good nights rest does wonders for the brain. So I woke up understanding how this works...but also feeling silly for not seeing it earlier.
tl;dr - this code is inside the application
controller. Other controllers don't call this code. That's why it works correctly.
Longer Answer:
Rails tries to find layouts based on the controller name. If a layout doesn't exist then rails will use the application
layout.
So in my Home
controller rails first looks for a home
layout. Since there is one it uses that layout.
I'm not sure what devise does but it's not looking for a layout named devise
so instead it uses application
layout. And that's when the code above runs. Since the controller is a devise controller the layout then gets changed to "layout_name_for_devise".
精彩评论