开发者

Reusing a custom "getter" in ruby

开发者 https://www.devze.com 2023-03-12 11:20 出处:网络
How can I make something like this...more compact? def token if authorized? return t.token else raise Error(\'unauthorized!\')

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号