Sni*_*gus 4 ruby methods controller ruby-on-rails declarative
我在控制器中出现了这个:
if not session[:admin]
flash[:notice] = "You don't have the rights to do #{:action}."
redirect_to :action=>:index
return
end
Run Code Online (Sandbox Code Playgroud)
它的兄弟姐妹:
if not session[:user] and not session[:admin]
flash[:notice] = "You don't have the rights to do #{:action}."
redirect_to :action=>:index
return
end
Run Code Online (Sandbox Code Playgroud)
当我想在一个方法中使用它时,我想将这一切减少到一个声明性行:
def action_which_requires_rights
require_rights :admin
#or:
#:require_rights :user_or_admin
end
Run Code Online (Sandbox Code Playgroud)
显然,如果require_rights失败,我不希望执行其余的方法.我发誓有办法做到这一点,但我找不到我读到的地方.我在想这个吗?
首先你可以做到:unless session[:admin]而不是if not ...
然后你可以有一个调用你的方法的前置过滤器,这个方法会做你的redirect_to"url"并返回.
我有一个问题,我希望你不只是将管理员的id存储在会话中作为你唯一的身份验证方式,在你的用户模型上有一个属性并查询可能是一个更安全的赌注.
正如其他人所说,before_filter似乎是正确的工具.但我会解决你所询问的实际模式.
不幸的是,方法不能使其调用方法返回.与您要查找的模式最接近的两个匹配项:
一个街区:
def require_rights(rights)
if session[rights]
yield
else
flash[:notice] = "You don't have the rights to do #{:action}."
redirect_to :action=>:index
end
end
Run Code Online (Sandbox Code Playgroud)
所以你要这样做:
def action_which_requires_rights
require_rights :admin do
#do whatever here
end
end
Run Code Online (Sandbox Code Playgroud)
或者返回值:
def require_rights(rights)
return true if session[rights]
flash[:notice] = "You don't have the rights to do #{:action}."
redirect_to :action=>:index
false
end
Run Code Online (Sandbox Code Playgroud)
所以你要这样做:
def action_which_requires_rights
require_rights :admin or return
#do whatever here
end
Run Code Online (Sandbox Code Playgroud)
我更喜欢这个块,因为它适合类似的方法,让调用者or return对我来说感觉有点不自然.
| 归档时间: |
|
| 查看次数: |
1598 次 |
| 最近记录: |