I have an API that takes a class as a configuration parameter, but I don't want to load the class (I'm using Rails) at the time that I'm setting up the API. I figured I could get around this by passing it an object that acts like the class in every way (by delegating to it) but doesn't actually reference the class, and thus load the class. until it us used.
This is what it expects:
MyAPI.configure.model = UserModel
But I'd like to give it something like:
MyAPI.configure.model = ->{ UserModel }
This is what I have. It works as well as expected but I have a feeling I take better advantage of Ruby's features and/or the standard library.
def lazy_delegate(&block)
delegate = BasicObject.new
def delegate.method_missing(message, *args)
@target ||= @target_block.call
@target.send message, *args
end
def delegate.__target__=(block)
@target_block = block
end
delegate.__target__ = block
delegate
end
I'm using this like:
MyAPI.configure.model = lazy_delegate{ UserModel }
Is there a better way to accomplish this? Does Ruby's standard library have anything that would make this cleaner?