Metaprogramming in controller: accessing instance variables


Hi all,

I’m trying to move a bunch of methods out of a controller into a
library that I can include and call a class method to have it
dynamically add a bunch of methods to the controller.

The goal is to just add to each controller:
include UIEnhancements::SubList
sub_list ‘Note’, ‘incomplete’

and have the sub_list method create all the methods needed to support
the sub_list ui…

Where I am running into trouble is that I want the meta-programmed
functions to have access to the instance vars (ie: @somethingorother
or @params) just like the hard coded ones I had in the controller to
begin with…

I’ve tried accessing via: instance_eval, instance_variable_get,
eval… all no good.

I have a file called “sub_list_system.rb” in the lib dir:

module UIEnhancements
module SubList

  def self.included(mod)
    class_eval { helper :SubList }

  module ClassMethods
    def sub_list( model = 'Note', parent = 'incomplete' )

      define_method("update_or_create_#{model.downcase.pluralize}") do
		#Some stuff
		eval( "@#{parent}" ) = 'test'


Does anyone know how to deal with this?

Thanks in advance!


eval( “@#{parent}” ) = ‘test’

That bit won’t work; eval doesn’t return a valid lvalue. You can try
instance_variable_set("@#{parent}", ‘test’) instead.