views:

44

answers:

1

Hi all,

I'm doing an application using mongodb and mongoid and I'm facing a problem where I need to map something in one document to something in another document. My plan is to store something in a document that I can then use to figure out what value for it to fetch from a different collection. But, this is more generally a ruby question about how I can fetch data from deep within a hash.

I have a structure something like this:

Widget
  Sections
    0
      Fields
        0
          value: foobar

If that makes sense. Let's say I want to get the value of the first field in the first section, I would do something like:

@widget.sections[0].fields[0].value

No problem.

Now the question is, how can I do this with all of that as a string? What I want to do is store within the database a mapping value. So I've have a key/value with something like:

mapping: "sections[0].fields[0].value"

Now how can I use that to get the data from @widget? I've tried @widget.send "sections[0].fields[0].value" but that does not work... I can do @widget.send "sections" and get back an array of sections, but I'm not quite sure how to take it further...

So to summarize, I can do this:

@widget.sections[0].fields[0].value

if I have @widget and a string "sections[0].fields[0].value" how can I execute that?

+1  A: 
@widget.instance_eval("sections[0].fields[0].value")

should do the trick.

Nathan