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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bf4e32e17fdfeab9753386289d521608?d=identicon&s=25 Luke Galea (Guest)
on 2005-12-30 23: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)
	    mod.extend(ClassMethods)
	    class_eval { helper :SubList }
	  end

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

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

Does anyone know how to deal with this?

Thanks in advance!
B554bcde846e4497eeffffc1399d3b09?d=identicon&s=25 Benjamin Stiglitz (Guest)
on 2005-12-31 04: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.

-Ben
This topic is locked and can not be replied to.