Accessing a class's containing namespace from within a module
Posted
by SFEley
on Stack Overflow
See other posts from Stack Overflow
or by SFEley
Published on 2010-03-20T03:22:26Z
Indexed on
2010/03/20
3:31 UTC
Read the original article
Hit count: 412
I'm working on a module that, among other things, will add some generic 'finder' type functionality to the class you mix it into. The problem: for reasons of convenience and aesthetics, I want to include some functionality outside the class, in the same scope as the class itself.
For example:
class User
include MyMagicMixin
end
# Should automagically enable:
User.name('Bob') # Returns first user named Bob
Users.name('Bob') # Returns ALL users named Bob
User(5) # Returns the user with an ID of 5
Users # Returns all users
I can do the functionality within these methods, no problem. And case 1 (User.name('Bob')
) is easy. Cases 2–4, however, require being able to create new classes and methods outside User
. The Module.included
method gives me access to the class, but not to its containing scope. There is no simple "parent" type method that I can see on Class nor Module. (For namespace, I mean, not superclass nor nested modules.)
The best way I can think to do this is with some string parsing on the class's #name
to break out its namespace, and then turn the string back into a constant. But that seems clumsy, and given that this is Ruby, I feel like there should be a more elegant way.
Does anyone have ideas? Or am I just being too clever for my own good?
© Stack Overflow or respective owner