Ross Bamford
1/26/2006 11:47:00 PM
On Thu, 26 Jan 2006 22:15:50 -0000, Ryan Hinton <iobass@email.com> wrote:
> Here is roughly what I want.
>
> module AttrWriterTrackModified
> def attr_writer(*syms)
> syms.each do |sym|
> eval("def #{sym}=(val)
> if @#{sym} != val
> @#{sym} = val
> @modified = true
> end
> end;")
> end
> end
> end
>
Maybe I'm missing something, but you're almost there. You could try this:
class Module
def attr_writer(*syms)
syms.each do |sym|
module_eval <<-EOC
def #{sym}=(val)
if @#{sym} != val
@#{sym} = val
@modified = true
end
end
EOC
end
end
end
Just use it as normal:
class TryIt
attr_reader :one, :two, :three, :modified
attr_writer :one, :two, :three
def initialize(one, two, three)
@one, @two, @three = one, two, three
@modified = false
end
end
p t = TryIt.new(1,2,3)
p t.one
p t.two
p t.three
p t.modified
p t.two = 4
p t.one
p t.two
p t.three
p t.modified
Output:
#<TryIt:0xb7facae4 @modified=false, @three=3, @two=2, @one=1>
1
2
3
false
1
4
3
true
(Hmm, I bet you could make an attr_initializer or something to cover that
initialize method too ... ;))
Hope that helps.
--
Ross Bamford - rosco@roscopeco.remove.co.uk