Created
January 2, 2009 15:40
-
-
Save oleganza/42569 to your computer and use it in GitHub Desktop.
This file contains 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 PluralizedConsts | |
P = self | |
def const_missing(sym) | |
return super(sym) if Thread.current[:pc_const_missed] | |
begin | |
super(sym) | |
rescue NameError => e | |
begin | |
Thread.current[:pc_const_missed] = true | |
P.full_const_get(self, P.singular_name_for_sym(sym)) | |
rescue NameError => e2 | |
# no singular form for the const sym | |
raise e | |
ensure | |
Thread.current[:pc_const_missed] = false | |
end | |
end | |
end | |
# Note: these methods depend on extlib gem. | |
# Override for your pleasure. | |
def self.singular_name_for_sym(sym) | |
sym.to_s.singular | |
end | |
def self.full_const_get(scope, str) | |
scope.full_const_get(str) | |
end | |
end | |
class <<Object | |
include PluralizedConsts | |
end | |
# | |
# Tests | |
# | |
if $0 == __FILE__ | |
require 'rubygems' | |
require 'extlib' | |
class Application | |
class Person | |
end | |
end | |
class Person | |
end | |
::Applications == Application or raise "Basic test failed" | |
::People == Person or raise "Basic test failed" | |
Applications == Application or raise "Basic test failed" | |
People == Person or raise "Basic test failed" | |
# Hardcore namespace issues | |
Application::People == Application::Person or raise "Hardcore test failed" | |
Applications::Person == Application::Person or raise "Very hardcore test failed" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment