-
-
Save yaroslav/42582 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 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" | |
# Real tests | |
People.new.class == Person or raise "initializer fail" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment