Also I typed get_const instead of const_get :(
On Thursday, 18 August 2011 at 3:19 PM, Samuel Richardson wrote:
> Dammit Paul, just as I was typing this out ;)
>
> There is a limitation in Pauls method though with nested Classes/Modules. If
> they are nested you can use something like:
>
> # Get a class based on a string, handles :: module nesting
> def self.class_from_string(str)
> str.split('::').inject(Object) do |mod, class_name|
> mod.const_get(class_name)
> end
> end
>
> Which will handle the nesting.
> Samuel Richardson
> www.richardson.co.nz (http://www.richardson.co.nz) | 0405 472 748
>
>
> On Thu, Aug 18, 2011 at 3:17 PM, Paul Annesley <[email protected]
> (mailto:[email protected])> wrote:
> > Check out
> > http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-constantize
> > (including the source code).
> >
> > It hinges on Kernel.get_const(string)
> >
> > - Paul
> >
> >
> > On Thursday, 18 August 2011 at 3:12 PM, Sonia Hamilton wrote:
> > > I'm just wondering about the Ruby way of instantiating a class when the
> > > class name is in a string?
> > >
> > > For example:
> > >
> > > def build_classname
> > > # reality is a bit more complex...
> > > "Foo" + "Builder"
> > > end
> > > class_name = build_classname
> > >
> > > Then I want to instantiate an instance based on class_name, ie the
> > > equivalent of:
> > >
> > > obj = FooBuilder.new
> > > # obj = class_name.new XX FAIL
> > >
> > > Google isn't helping - ruby + classname + instantiate + string brings up
> > > all sorts of random stuff :-) I was thinking of doing some eval
> > > awfulness, but there's got to be a Ruby way...
> > >
> > > --
> > > Sonia Hamilton
> > >
--
You received this message because you are subscribed to the Google Groups "Ruby
or Rails Oceania" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rails-oceania?hl=en.