在我的一个助手中,无论用户是否在个人资料上,我都必须有所不同。帮助程序返回一个充满URL的数组。
def get_options(profile)
if profile
url_arr = profile_infinite_path(user, ...)
# .
# .
# do stuff with profile_infinite_path
else
url_arr = infinite_path(user, ...)
# .
# .
# do same stuff with infinite_path
end
end
我想使此代码更干燥,所以我的计划是将路径存储为变量,然后仅将所有其余代码仅调用一次。
def get_options(profile)
if profile
var_path = profile_infinite_path
else
var_path = infinite_path
end
url_arr = var_path(user, ...)
# .
# .
# do stuff with var_path
end
我也尝试将路径存储为一种方法,但是没有运气。
var_path = profile_infinite_path.method
您在这里有两个选择。由于路径助手是方法,并且只需声明它们就可以在没有参数的情况下调用方法,path = profile_inifite_path
因此像这样的赋值给出了方法调用的结果。
您可以通过使用符号来引用该方法来延迟调用,然后在需要时将其作为消息发送:
var_path = :profile_infinite_path
# ...
send(var_path, user, ...)
该符号是的第一个参数send
,后跟您将要给该方法的所有参数。
处理此问题的另一种方法是将方法调用包装在proc中,并在需要时调用它:
var_path = ->(*args){ profile_infinite_path(*args) }
# ...
var_path.call(user, ...)
我倾向于这样send
的情况。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句