ぐらめぬ・ぜぷつぇんのはてダ(2007 to 2011)

2007年~2011年ごろまで はてなダイアリー に書いてた記事を引っ越してきました。

symfonyで言うところの"forward()"的なメソッドについて

symfonyではforward()とredirect()は厳密に区別されます。redirect()はHTTP 302 + Locationヘッダーを送信しますが、forward()は内部的にアクションメソッドをdispatchさせます。またそれに伴い、Viewもdispatchされた先のアクションメソッドに従います。

Akelos、というかRailsの場合は、HTTP302RedirectについてはredirectToメソッドが担当します。で、forward()メソッドについてはrenderメソッドが実はその役を担っています。

Akelosの場合:

function アクション名() {
 ...
 return $this->renderAction(array('action' => 'dispatch先のaction名'));
}

Railsの場合:

def アクション名
 render :action => "dispatch先のaction名"
end

Akelosの場合、通常のrender()メソッドを呼んでしまうと、結果的にrenderWithoutLayout()が呼ばれてしまい、layoutがrenderingされない、という点に注意する必要があります。以前もどこかで書きましたが、AkActionController#render()は引数の内容に応じてrenderHogeHoge()を内部で切り替えて呼び出していますが、render()経由だとrenderAction()の$with_layoutがnullか何か、とにかく偽として判断される値が渡ってしまい、renderWithoutLayout()が呼ばれてしまう・・・というのが内部的な話です。

return $this->render(array('action' => '...', 'layout' => true));

とすれば、renderAction()の$with_layout引数にtrueが渡り、renderWithLayout()を呼んでくれます。

AkelosRailsによく似ていますが完全なコピーでは無いようです。例えばこのrender()とlayoutの関係については、実はRailsはこれとは反対に、'layout'はデフォルトではtrueとされていて、layoutを無効化したり切り替えたい場合にのみ、明示的にfalseや別のlayout名を設定します。

# Renders the template for the action "goal" within the current controller
render :action => "goal"

# Renders the template for the action "short_goal" within the current controller,
# but without the current active layout
render :action => "short_goal", :layout => false

# Renders the template for the action "long_goal" within the current controller,
# but with a custom layout
render :action => "long_goal", :layout => "spectacular"

ActionController::Base

さて・・・今回はどこで嵌ったかというと、てっきりメソッド呼び出しのチェーンで行けると勘違いしてたんですよ。

function index() {
    return $this->foo();
}
function foo() {
 ...
}

これは実はNGで、View名は相変わらずindexのままなので、indexアクション用のViewが使われてしまいます。

で、いい加減ぶち切れてRailsのドキュメントを読んで解決しました。

AkelsoのAkActionControllerのAPIページ
http://api.akelos.org/ActionController/Base/AkActionController.html

RailsActionController::BaseのAPIページ
http://api.rubyonrails.org/classes/ActionController/Base.html

・・・
最初からRailsAPIページ見ときゃ良かった。
ウワァァ−−−−−。゚(゚´Д`゚)゚。−−−−−ン!!!! 

・・・何だろう。なんで、RailsAPIページはこう、すぅっと心に染みいってくるのだろう・・・。
それに引き替えAkelosはぁぁあああああああ!!!!!!!!!!