I try to create a gem that performs a call to an API and returns an
HTTParty::Response
MyGem.list_all
#<HTTParty::Response:0x7fb859922908 parsed_response={...}>
Mygem.list_all.total_count
> 22
module MyGem
class << self
def list_all
@list_all ||= Get.new('list_all')
end
end
class Get
def initialize(path)
@get ||= get(path)
end
def total_count
@get['total_count']
end
def get(path)
HTTParty.get(url+path)
end
end
end
HTTParty::Response
Mygem.list_all.total_count
> 22
MyGem.list_all
MyGem::Get
@get
HTTParty::Response
#<MyGem::Get:0x007fb26d10f4b0 @get=HTTParty response...
new
total_count
MyGem.list_all
#<HTTParty::Response:0x7fb859922908 parsed_response={...}>
The rule of thumb is: whether you want to chain, return self
from each single method, and implement everything you expect to retrieve from any subsequent method by delegation to self
.
module MyGem
class << self
def list_all
@list_all ||= Get.new('list_all')
end
class Get < BasicObject
def initialize(path)
@get ||= get(path)
end
HTTParty::Response.instance_methods(true).each do |m|
meth = m # damn ruby closures
define_method meth do |*args, &λ|
@get.public_send(meth, *args, &λ)
end
end
end
end
end