Abstracting out adapters - Dependency Injection

Just wanted to add that you can declare types on those abstract methods for the interface:

module RedisInstance
  abstract def flushall : Nil
  abstract def zcount(key : String, min : Int32, max : Int32) : Int32
  abstract def hgetall(key) : Array(String)
  # etc.
end
 
class MyClass
  include RedisInstance
 
  def flushall : Nil
    puts "flushed"
  end
 
  def zcount(key : String, min : Int32, max : Int32) : Int32
    1
  end
 
  def hgetall(key) : Array(String)
    [] of String
  end
  
  # etc.
end
 
my_class = MyClass.new
if my_class.is_a?(RedisInstance)
  puts "my_class is a RedisInstance"
else
  puts "my_class is not a RedisInstance"
end
# => my_class is a RedisInstance

Also, I second that RFC.

1 Like