-
-
Save tal/2829246 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 Helpers | |
def self.constantize(camel_cased_word) | |
names = camel_cased_word.split('::') | |
names.shift if names.empty? || names.first.empty? | |
constant = Object | |
names.each do |name| | |
constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name) | |
end | |
constant | |
end | |
end | |
class String | |
def constantize | |
Helpers.constantize(self) | |
end | |
end | |
module HasProviderSubclass | |
module ClassMethods | |
def type_to_class_string type | |
@type_to_class_string ||= Hash.new do |h, type| | |
h[type] = "#{self.to_s.split('::').first}::#{type.capitalize}" | |
end | |
@type_to_class_string[type] | |
end | |
def type_to_class type | |
@type_to_class ||= Hash.new { |h, cs| h[cs] = type_to_class_string(cs).constantize } | |
@type_to_class[type] | |
end | |
private | |
def __setup_provider_variables | |
@type_to_class_string = Hash.new do |h, type| | |
h[type] = "#{self.to_s.split('::').first}::#{type.capitalize}" | |
end | |
@type_to_class = Hash.new { |h, cs| h[cs] = type_to_class_string(cs).constantize } | |
end | |
end | |
module InstanceMethods | |
end | |
def self.included(receiver) | |
receiver.extend ClassMethods | |
receiver.send :include, InstanceMethods | |
end | |
end | |
class UserIdentifier | |
include HasProviderSubclass | |
class Facebook < UserIdentifier | |
end | |
end | |
class ExternalContactList | |
include HasProviderSubclass | |
class Facebook < ExternalContactList | |
end | |
end | |
# Intended Behavior: | |
puts ExternalContactList.type_to_class('facebook') # => ExternalContactList::Facebook | |
puts UserIdentifier.type_to_class('facebook') # => UserIdentifier::Facebook | |
puts UserIdentifier::Facebook.type_to_class('facebook') # => UserIdentifier::Facebook | |
# Actual Behavior | |
puts ExternalContactList.type_to_class('facebook') # => UserIdentifier::Facebook | |
puts UserIdentifier.type_to_class('facebook') # => UserIdentifier::Facebook | |
puts UserIdentifier::Facebook.type_to_class('facebook') # => UserIdentifier::Facebook |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment