Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.