Skip to content

Instantly share code, notes, and snippets.

@agibralter
Forked from tal/mixin.rb
Created May 29, 2012 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save agibralter/2829193 to your computer and use it in GitHub Desktop.
Save agibralter/2829193 to your computer and use it in GitHub Desktop.
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[type]
end
def type_to_class type
@type_to_class[type]
end
private
def __setup_provider_variables
@type_to_class_string = Hash.new { |h, type| h[type] = "#{self.to_s}::#{type.capitalize}" }
@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
receiver.send :__setup_provider_variables
end
end
class UserIdentifier
include HasProviderSubclass
class Facebook
end
end
class ExternalContactList
include HasProviderSubclass
class Facebook
end
end
# Intended Behavior:
puts ExternalContactList.type_to_class('facebook') # => ExternalContactList::Facebook
puts UserIdentifier.type_to_class('facebook') # => UserIdentifier::Facebook
# Actual Behavior
puts ExternalContactList.type_to_class('facebook') # => UserIdentifier::Facebook
puts UserIdentifier.type_to_class('facebook') # => UserIdentifier::Facebook
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment