Created
November 26, 2013 00:40
-
-
Save tatey/7651520 to your computer and use it in GitHub Desktop.
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 Designate | |
# Declare an instance method to become the designated method for | |
# that class. Arguments are correctly passed to instance method | |
# and initializer. | |
# | |
# Example with a desginated method that takes no arguments: | |
# | |
# class Generator | |
# extend Designate | |
# | |
# def initialize attributes = {} | |
# @attr1 = attributes[:attr1] | |
# end | |
# | |
# def generate | |
# end | |
# designate :generate | |
# end | |
# | |
# Generator.generate attr1: val1 | |
# | |
# Example with a desginated method that takes arguments: | |
# | |
# class Generator | |
# extend Designate | |
# | |
# def initialize attributes = {} | |
# @attr1 = attributes[:attr1] | |
# end | |
# | |
# def generate arg1 | |
# end | |
# designate :generate | |
# end | |
# | |
# Generator.generate val1, attr1: val2 | |
def designate method_symbol | |
meth = instance_method method_symbol | |
arity = meth.arity | |
define_singleton_method method_symbol do |*args| | |
class_args = args.slice! arity..-1 | |
instance_args = args | |
new(*class_args).public_send method_symbol, *instance_args | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment