Skip to content

Instantly share code, notes, and snippets.

@oleganza
Created January 2, 2009 15:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oleganza/42569 to your computer and use it in GitHub Desktop.
Save oleganza/42569 to your computer and use it in GitHub Desktop.
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