get class instance from name?

Discussion in 'Ruby' started by Kevin McConnell, Apr 26, 2005.

  1. What's a good way to get at a Class instance, from a string containing
    its name?

    For example, say I have a string "Customer", and want to call
    Customer.my_class_method(). I realise I could do something like:

    # class_name = "Customer"
    result = eval("#{class_name}.my_class_method()")

    ....but it smells like a hack to me, and so I suspect there's a more
    "proper" way to get at the object I need...

    Any pointers would be much appreciated!

    Cheers,
    Kevin
    Kevin McConnell, Apr 26, 2005
    #1
    1. Advertising

  2. On Apr 25, 2005, at 7:04 PM, Kevin McConnell wrote:

    > What's a good way to get at a Class instance, from a string containing
    > its name?
    >
    > For example, say I have a string "Customer", and want to call
    > Customer.my_class_method(). I realise I could do something like:
    >
    > # class_name = "Customer"
    > result = eval("#{class_name}.my_class_method()")
    >
    > ....but it smells like a hack to me, and so I suspect there's a more
    > "proper" way to get at the object I need...
    >
    > Any pointers would be much appreciated!


    You're looking for Module.const_get(). Use it to get the class object,
    then call the method.

    Hope that helps.

    James Edward Gray II
    James Edward Gray II, Apr 26, 2005
    #2
    1. Advertising

  3. James Edward Gray II wrote:

    > You're looking for Module.const_get(). Use it to get the class object,
    > then call the method.


    Yep, that's exactly what I needed.

    Thanks!
    Kevin McConnell, Apr 26, 2005
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Sridhar R
    Replies:
    14
    Views:
    1,384
    =?iso-8859-1?Q?Fran=E7ois?= Pinard
    Feb 10, 2004
  2. dotNeter
    Replies:
    9
    Views:
    516
    James Kanze
    Mar 17, 2008
  3. dmitrey
    Replies:
    4
    Views:
    240
    dmitrey
    Oct 4, 2008
  4. Bryan
    Replies:
    6
    Views:
    265
    Terry Reedy
    Jun 24, 2009
  5. Martin P. Hellwig
    Replies:
    1
    Views:
    367
    Martin P. Hellwig
    Mar 26, 2010
Loading...

Share This Page