Reusing a custom "getter" in ruby
How can I make something like this...more compact?
def token
if authorized?
return t.token
else
raise Error('unauthorized!')
end
end
def secret
if authorized?
return t.secret
else开发者_JAVA技巧
raise Error('unauthorized!')
end
end
Feels like way too much re-use at the moment.
Add a filter that will run before the token or secret methods are called.
before_filter :check_authorization, :only => [ :token, :secret ]
Then add a method that will check if user is authorized,
def check_authorization
if !authorized?
raise DropboxError('User is not authorized')
end
end
def token
@token
end
def secret
@secret
end
If token and secret are already properties of your model defined with :attr_accessor
or something like that, you could eliminate the token and secret methods altogether as they are simple getters with no logic.
精彩评论