From: Peter Cooper Date: 2007-05-30T19:24:14+09:00 Subject: Re: Help with simple meta programming ------=_Part_1253_23732826.1180520653432 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 5/30/07, mario.lopes@gmail.com wrote: > > I want to change/create a new attr_accessor such that it calls a kind > of proxy for retrieving the variable (which is not actually stored in > the object itself but rather on the database). > > def variable > invoke_method(variable) > ... > end > > def variable=(value) > invoke_method(variable, value) > ... > end There are a few ways to do this, and I'm surprised you haven't had a few answers yet! So.. I'll provide some pointers in code. You will need to tidy this up and structure it better, but it should at least demonstrate a concept.. class Module # Why in Module and not Class? Because otherwise you couldn't use it # within module definitions.. only classes, whereas Module lets you cover # both.. def attr_proxied_accessor(var) define_method(var) do # At this stage, we're defining the "x" method.. 10 end define_method(:"#{var}=") do |v| # At this stage, we're defining the "x=" method.. end end end class Something attr_proxied_accessor :x end puts Something.new.x There's still some way to go, such as actually calling your proxy routines and doing the "instance variable set/get", but it should at least crack the biggest problem..? If you continue to get stuck, Googling around looking for full code to attr_accessor provides a few techniques. Cheers, Peter Cooper http://www.rubyinside.com/ ------=_Part_1253_23732826.1180520653432--