Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby interface classes?

Tags:

oop

ruby

I have the following classes:

CachedObject
CachedObjectSource
CachedObjectDbSource < CachedObjectSource
CachedObjectDalliSource < CachedObjectSource

CachedObject is a non-database object that is getting pulled from a third-party API and stored locally. CachedObject will be stored in both the database and Dalli (memcache), the real-time code will ping the Dalli source for a copy of the object, and the Dalli source will search the database source and update its cache if the object does not exist. So it's a nested call that requires each child class of CachedObjectSource to implement the same set of methods. IE, an interface.

Is there a way to write the CachedObjectSource class so that its child classes must implement the interface? Am I going about this the wrong way?

like image 217
kid_drew Avatar asked Sep 11 '13 15:09

kid_drew


People also ask

What is an interface in Ruby?

In particular, in Ruby, the Interface of an object is determined by what it can do, not what class is is, or what module it mixes in. Any object that has a << method can be appended to.

What are classes in Ruby?

What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.

Are there classes in Ruby?

Classes in Ruby are first-class objects—each is an instance of class Class . When a new class is created, an object of type Class is initialized and assigned to a global constant ( Name in this case). Classes, modules, and objects are interrelated.

What is the difference between modules and classes in Ruby?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).


1 Answers

Ruby doesn't know interfaces similar to e.g. Java. Instead, Ruby programs typically use an approach called Duck Typing which basically means that you can send any message to any object which then can decide if it will respond to that, i.e. each object decides on its own which methods it has.

The closest thing you can get to an "interface" is a class (or module) that implements a method but only raises a NotImplementedError similar to this:

class CachedObjectSource
  def my_method
    raise NotImplementedError, "Implement this method in a child class"
  end
end

That way, the method will be present and return a sensible error when called without being overwritten in a child class. Then, you should write some documentation making it clear what child classes have to implement to be compliant.

like image 158
Holger Just Avatar answered Oct 25 '22 18:10

Holger Just