dom*_*dom 0 ruby methods ruby-on-rails
我正在公司的一个RoR应用程序中查看一些代码。而且我注意到,有时使用带问号的方法,例如我们的控制器之一使用的以下方法。
# readonly checker
# @param url to redirect or nil
# if url set up, goes to url with note "not allowed because readonly"
# else @returns true / false
def readonly?(url = nil)
if current_user_can_access?(:readonly)
message = I18n.t(:auth_readonly)
if request.xhr?
response.status = 403
render json: { error: message }
else
redirect_to url, notice: message unless url.nil?
end
true
else
false
end
end
Run Code Online (Sandbox Code Playgroud)
我的问题是,是否可以接受(并且通常),这readonly?还会重定向到某个地方。
我习惯于实现问号方法,该方法仅返回可转换为布尔值的值,并且不对模型,DB进行更改。
具有副作用的谓词方法违反了最小惊讶原则 IMO。它可能具有“内部”副作用,例如记住一些内部值,但是应该“外部”纯净/参照透明。
如果您订阅了Bertrand Meyer的Command-Query Separation Principle,那么谓词方法就是Queries(不应该有副作用)。redirect_to是一个Command(仅具有副作用,没有返回值)。两者不应混用。