Skip to content

Instantly share code, notes, and snippets.

@ippeiukai
Created June 17, 2016 07:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ippeiukai/7a3e3e49c26fc278c0b33a235db37e86 to your computer and use it in GitHub Desktop.
Save ippeiukai/7a3e3e49c26fc278c0b33a235db37e86 to your computer and use it in GitHub Desktop.
Singleton but as convenient as class methods; it's both.
module SingletonWithClassDelegator
extend ActiveSupport::Concern
included do
include Singleton
original_delegate_method = method(:delegate).unbind if self.respond_to?(:delegate)
extend SingleForwardable
if original_delegate_method.present?
# restore the delegate of ActiveSupport that has been overshadowed by SingleForwardable
define_singleton_method :delegate, original_delegate_method
end
end
class_methods do
# delegates methods to the singleton instance
def method_missing(method_name, *args, &block)
if instance.respond_to?(method_name)
def_single_delegator :instance, method_name
public_send(method_name, *args, &block)
else
super
end
end
def respond_to_missing?(method_name, *_args)
instance.respond_to?(method_name) || super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment