Reputation: 1207
Is there a way to do this in ruby?
a = UnauthenticatedClient.new
a.class #=> #<UnauthenticatedClient>
a.login!("username", "password")
a.class #=> #<AuthenticatedClient>
Upvotes: 1
Views: 53
Reputation: 37409
No, but you can do this:
a = UnauthenticatedClient.new
a.class #=> #<Unauthenticated>
a = a.login!("username", "password")
a.class #=> #<Authenticated>
A method may return a different object, but it cannot change the reference to that object:
class UnauthenticatedClient
def login!(username, password)
# do the login process...
Authenticated.new(authentication_params) # returns a new object of type Authenticated
end
end
You can also consider using attributes instead of classes to determine whether the client is authenticated or not:
a = Client.new
a.class #=> #<Client>
a.authenticated? # false
a.login!("username", "password")
a.class #=> #<Client>
a.authenticated? # true
Upvotes: 2