有没有办法在ruby中执行此操作?
a = UnauthenticatedClient.new
a.class #=> #<UnauthenticatedClient>
a.login!("username", "password")
a.class #=> #<AuthenticatedClient>
答案 0 :(得分:2)
不,但你可以这样做:
a = UnauthenticatedClient.new
a.class #=> #<Unauthenticated>
a = a.login!("username", "password")
a.class #=> #<Authenticated>
方法可能会返回不同的对象,但不能更改对该对象的引用:
class UnauthenticatedClient
def login!(username, password)
# do the login process...
Authenticated.new(authentication_params) # returns a new object of type Authenticated
end
end
您还可以考虑使用属性而不是类来确定客户端是否经过身份验证:
a = Client.new
a.class #=> #<Client>
a.authenticated? # false
a.login!("username", "password")
a.class #=> #<Client>
a.authenticated? # true