Getting Object From String?

Discussion in 'Ruby' started by Hunter's Lists, Dec 14, 2005.

  1. Howdy,

    I have a class called 'NewsItem'.

    In one of my Rails classes, I have a place to pass in a string (from a HTTP
    parameter). That string's value is 'NewsItem', the class name.

    How can I convert that to use as the class?

    I.e.

    @model = params[:modelname]
    @items = @model.find:)all)

    This doesn't work. I was hoping it would work the same way as:
    @items = NewsItem.find:)all)

    How can I pull this off?

    Thanks!
    Hunter's Lists, Dec 14, 2005
    #1
    1. Advertising

  2. Hunter's Lists wrote:
    > Howdy,
    >
    > I have a class called 'NewsItem'.
    >
    > In one of my Rails classes, I have a place to pass in a string (from a
    > HTTP
    > parameter). That string's value is 'NewsItem', the class name.
    >
    > How can I convert that to use as the class?
    >
    > I.e.
    >
    > @model = params[:modelname]
    > @items = @model.find:)all)
    >
    > This doesn't work. I was hoping it would work the same way as:
    > @items = NewsItem.find:)all)
    >
    > How can I pull this off?


    # This takes into account nested class names
    @model = params[:modelname].split('::').inject(Object) {|parent, klass|
    parent.const_get klass}

    > Thanks!



    E

    --
    Posted via http://www.ruby-forum.com/.
    Eero Saynatkari, Dec 14, 2005
    #2
    1. Advertising

  3. On Dec 14, 2005, at 4:10 PM, Hunter's Lists wrote:

    > Howdy,
    >
    > I have a class called 'NewsItem'.
    >
    > In one of my Rails classes, I have a place to pass in a string
    > (from a HTTP
    > parameter). That string's value is 'NewsItem', the class name.
    >
    > How can I convert that to use as the class?
    >
    > I.e.
    >
    > @model = params[:modelname]
    > @items = @model.find:)all)


    Try changing the last line to:

    @items = Object.const_get(@model).find:)all)

    Hope that helps.

    James Edward Gray II
    James Edward Gray II, Dec 14, 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. ankur
    Replies:
    1
    Views:
    12,701
    Jan =?UTF-8?B?VGhvbcOk?=
    Aug 27, 2007
  2. Rakesh
    Replies:
    10
    Views:
    12,146
    Mike Schilling
    Apr 8, 2008
  3. Rominsky
    Replies:
    5
    Views:
    251
    André
    Dec 18, 2008
  4. Jean-Paul Calderone

    Re: getting object instead of string from dir()

    Jean-Paul Calderone, Dec 17, 2008, in forum: Python
    Replies:
    2
    Views:
    263
  5. Martin
    Replies:
    6
    Views:
    172
    Richard Cornford
    Aug 20, 2004
Loading...

Share This Page