It's actually a bit more complete than Kevin's in that it correctly inspects
the contents of the string before trying to get a constant. in other words,
if the class Mammal::Dog didn't exists, "Mammal::Dog".constantize would
would raise a NameError exception.
Object.mod_eval will evaluate the given string within the context of the
Object module (global). The two additional arguments __FILE__ and __LINE__
are for outputting useful debugging information if there is an error (which
file and line the error occurred).
--Jordan
On Fri, Apr 18, 2008 at 3:30 PM, Rob Kaufman <[EMAIL PROTECTED]> wrote:
> OK,
> My curiosity got the better of me and I looked it up. Rails does this:
>
> def constantize(camel_cased_word)
> unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
> raise NameError, "#{camel_cased_word.inspect} is not a valid
> constant name!"
> end
>
> Object.module_eval("::#{$1}", __FILE__, __LINE__)
> end
>
> Which doesn't seem as good as what Kevin is showing.
>
> Anyone have any thoughts?
> Rob
>
>
> On Fri, Apr 18, 2008 at 11:09 AM, Kevin Clark <[EMAIL PROTECTED]>
> wrote:
>
> >
> > On Fri, Apr 18, 2008 at 10:46 AM, Rob Kaufman <[EMAIL PROTECTED]>
> > wrote:
> > > Its worth noting that Kevin's method is Ruby, where constantize is
> > Rails
> > > sugar.
> > >
> > > Cheers,
> > > Rob
> >
> > Also, I think constantize is implemented like this:
> >
> > class String
> > def constantize
> > self.split("::").inject(Object) do |enclosing_class, name_segment|
> > enclosing_class.const_get(name_segment)
> > end
> > end
> > end
> >
> > (atleast that's how I'd implement it)
> >
> > So it actually takes strings that may have namespacing and grabs the
> > constant properly. Pure `const_get` can't do that.
> >
> > --
> > Kevin Clark
> > http://glu.ttono.us
> >
> >
> >
>
> >
>
--
Jordan A. Fowler
2621 First Ave Apt 5
San Diego, CA 92103
E-mail: [EMAIL PROTECTED]
Website: http://www.jordanfowler.com
Phone: 406.546.8055
--~--~---------~--~----~------------~-------~--~----~
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby
-~----------~----~----~----~------~----~------~--~---