Created
June 17, 2016 07:53
-
-
Save ippeiukai/7a3e3e49c26fc278c0b33a235db37e86 to your computer and use it in GitHub Desktop.
Singleton but as convenient as class methods; it's both.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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