Ruby on rails 重复使用自定义文件;“吸气剂”;红宝石色
我怎样才能使这样的东西…更紧凑Ruby on rails 重复使用自定义文件;“吸气剂”;红宝石色,ruby-on-rails,ruby,Ruby On Rails,Ruby,我怎样才能使这样的东西…更紧凑 def token if authorized? return t.token else raise Error('unauthorized!') end end def secret if authorized? return t.secret else raise Error('unauthorized!') end end 现在感觉重复使用太多了。添加一个过滤器,该过滤器将在调用令牌或秘密方法之前
def token
if authorized?
return t.token
else
raise Error('unauthorized!')
end
end
def secret
if authorized?
return t.secret
else
raise Error('unauthorized!')
end
end
现在感觉重复使用太多了。添加一个过滤器,该过滤器将在调用令牌或秘密方法之前运行
before_filter :check_authorization, :only => [ :token, :secret ]
然后添加一个检查用户是否已授权的方法
def check_authorization
if !authorized?
raise DropboxError('User is not authorized')
end
end
def token
@token
end
def secret
@secret
end
如果token和secret已经是用
:attr\u accessor
或类似的东西定义的模型的属性,您可以完全消除token和secret方法,因为它们是没有逻辑的简单getter。添加将在调用token或secret方法之前运行的筛选器
before_filter :check_authorization, :only => [ :token, :secret ]
然后添加一个检查用户是否已授权的方法
def check_authorization
if !authorized?
raise DropboxError('User is not authorized')
end
end
def token
@token
end
def secret
@secret
end
如果token和secret已经是用
:attr\u accessor
或类似的东西定义的模型的属性,您可以完全消除token和secret方法,因为它们是简单的getter,没有逻辑。在第3行返回token
,但在此范围内,“token”除了作为方法本身之外不存在,在这种情况下会导致无限递归。第9行的secret
也一样。你省略了一些代码吗?拥有完整的代码将帮助我们提供最好的答案。@Jordan:考虑到原始代码中缺少end
,这意味着代码段不会编译,我认为他编译了。在第3行,您返回token
,但在此范围内,“token”除了作为方法本身之外不存在,在这种情况下会导致无限递归。第9行的secret
也一样。你省略了一些代码吗?拥有完整的代码将帮助我们提供最佳答案。@Jordan:考虑到原始代码中缺少end
,这意味着代码片段无法编译,我认为他做到了。