Reputation: 7505
I'm currently developing a central authentication API(in ruby on rails) which will authenticate with many other providers based on the domain of a user's email address.
If I was using java, this would be a classic use case for interfaces. Given that I am using Ruby, I would still like to use the interface construct, but not really sure how to enforce the implementation of interface methods.
The intention for this interface is to have one authenticated?
method, for now at least.
An example implementation. It authenticates a user in a local database.
# internal_user.rb
class InternalUser < User
def authenticated?(email, password)
user = User.find_for_database_authentication(email: email)
user && user.valid_password?(password) && !user.confirmed_at.nil?
end
end
So when I add more provider support to my API(i.e. more classes that implement this interface), how can I ensure that these new classes are going to implement this interface, in other words, ensure that the authenticated?
method has been implemented?
Upvotes: 1
Views: 1082
Reputation: 54263
Ruby doesn't have any interface similar to Java. With duck-typing, it's up to each class to decide if it answers a method call or not.
If you want to show that a method should be implemented in a subclass, you could raise an exception in the parent method :
class User
def authenticated?(*p)
raise NotImplementedError, "IMPLEMENT ME IN #{self.class}##{__method__}"
end
end
class InternalUser < User
end
InternalUser.new.authenticated?('user', '[email protected]')
#interface.rb:3:in `authenticated?': IMPLEMENT ME IN InternalUser#authenticated? (NotImplementedError)
Upvotes: 3