Add dynamic instance methods in a controller class

L

Luc Juggery

Hello All,

I have a problem while developping an application using rails.
In fact, this is more a general question on Ruby methods.
I'd like to add some methods to my controller depending upon some
parameters read from an xml file during initialisation (I hope I am
quite clear :) )
Below is the code I am using:

----------------
require 'rexml/Document'
include REXML

class MyController < ApplicationController

def index
# Xsd is a model (not ActiveRecord that is used to get
values from an XML file
xsd = Xsd.new("myfile.xsd")

# Get main section
@main_sections = xsd.get_main_sections

# Get item for first section
@item = xsd.get_items_per_section(@main_sections[0].to_s)

# Dynamically create method for to retrieve list of fields for each
main sections
# THIS PART IS NOT WORKING
@main_sections.each do |section|
self.instance_eval{ define_method("get_item_for_#{section}") {"toto"}}
end
end
end
-----------------


While testing this, I have an error message saying that the
define_method does not exist !!!!
Why is this method not found ???
I am still not sure about the instance_eval, class_eval, define_method
I need to use.
Do you have any clues regarding this problem ?

Thanks a lot,

Luc
 
G

Gabriele Marrone

Il giorno 04/nov/06, alle ore 16:03, Luc Juggery ha scritto:
# THIS PART IS NOT WORKING
@main_sections.each do |section|
self.instance_eval{ define_method("get_item_for_#{section}")
{"toto"}}
end

I suggest something like:

@main_sections.each do |section|
eval %Q(
def get_item_for_#{section}
"toto"
end
)
end

I didn't try it but I think it should work.
 
L

Luc Juggery

Thanks a lot, I have post it in rubyonrails-talk.
Sorry for this but I though this was more linked to ruby than to rails.
Luc
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top