Created
October 8, 2012 01:16
-
-
Save tal/3850230 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 HasProviderSubclass | |
| USERS = [] | |
| module ClassMethods | |
| def type_to_class_string type | |
| @type_to_class_string ||= Hash.new do |h, type| | |
| h[type] = "#{self.to_s}::#{type.classify}" | |
| end | |
| @type_to_class_string[type] | |
| end | |
| def type_to_class type | |
| @type_to_class ||= Hash.new do |h, cs| | |
| h[cs] = type_to_class_string(cs).constantize | |
| end | |
| @type_to_class[type] | |
| end | |
| # alias call type_to_class | |
| end | |
| module InstanceMethods | |
| def type | |
| self.class.to_s.demodulize.underscore | |
| end | |
| end | |
| def self.included(receiver) | |
| USERS << receiver | |
| receiver.extend ClassMethods | |
| receiver.send :include, InstanceMethods | |
| # Makes Klass('type') a method | |
| tree = receiver.to_s.split("::") | |
| klass = tree.pop | |
| if tree.empty? | |
| Kernel.module_eval do | |
| define_method klass do |type| | |
| receiver.type_to_class(type) | |
| end | |
| end | |
| else | |
| namespace = tree.join("::").constantize | |
| puts "Defining method #{klass} on namespace #{namespace}" | |
| namespace.module_eval do | |
| define_singleton_method klass do |type| | |
| receiver.type_to_class(type) | |
| end | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment