Add dynamic instance methods in a controller class

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 :slight_smile: )
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

Luc Juggery wrote:

I have a problem while developping an application using rails.

[snip]

You might have better luck asking this question on the Rails group:
http://groups.google.com/group/rubyonrails-talk

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.

路路路

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

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