Forum: Ruby on Rails metaprogramming in controller: accessing instance variables

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Luke Galea (Guest)
on 2005-12-31 00:07
(Received via mailing list)
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!
Benjamin S. (Guest)
on 2005-12-31 05:08
(Received via mailing list)
> eval( "@#{parent}" ) = 'test'

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

This topic is locked and can not be replied to.