我是 Ruby on Rails 的新手。几个小时前开始学习 Ruby 和 Ruby on Rails,并尝试将它的 DRY 原则应用到我自己的 Laravel 代码中。
这就是我的 RoR 的样子:
class WeddingController < ApplicationController
before_filter :get_wedding
def get_wedding
/*
If Wedding.find(2) returns false, redirect homepage
Else, bind @wedding into all methods for use
*/
end
def edit
@wedding //this method has access to @wedding, which contains Wedding.find(2) data.
end
def update
//Same as above method
end
def destroy
//Same as above method, can do things like @wedding.destroy
end
end
这就是我的 Laravel 的样子
class Wedding_Controller extends Base_Controller {
public function edit($id)
{
if(Wedding::find($id) === false)
return Redirect::to('/);
//Edit code
}
public function update($id)
{
if(Wedding::find($id) === false)
return Redirect::to('/);
//Update code
}
public function destroy($id)
{
if(Wedding::find($id) === false)
return Redirect::to('/);
//Destroy code
}
}
- 我怎样才能 DRY
if(Wedding::find($id) === false)
检查就像我的 RoR 代码? - 如果
Wedding::find($id) returns actual Wedding data
,我怎样才能像$wedding variable
在所有指定的方法中一样注入它?(如果可能,不要使用类范围寻找任何东西。)
非常感谢!
附言。对于不了解我的 RoR 脚本的人;基本上它就是这样做的。
Before any method call on this controller, execute get_wedding method first.
If get_wedding can't find the wedding in database, let it redirect to homepage.
If get_wedding finds the wedding in database, inject returned value as @wedding variable to all methods so they can make use of it. (e.g destroy method calling @wedding.destroy() directly.)