Thanks Jesus and Robert! But the case is quite more complex because (I
forgot to mention in original message) I'm not calling B#save directly -
it's a part of a big class which builds many objects and the option is
either replace all .save with .save(false) or to make some monkey magic.
The B class might go into some lib or plugin (but not sure yet) so I
need to find a way for this case also.
My friend and I came to this kind of solution:
class B
def initialize
@a=A.new
@a.instance_eval <<-EOF
alias :old_save :save
def save(validate = false)
old_save(validate)
end
EOF
end
The only thing that this would save without validation only one time, if
there'd be smth like
class B
def initialize
@a1 = A.new
@a2 = A.new
end
def save
@a1.save
@a2.save # it wouldn't work here or I'd need to define same methods
n times
end
end
I will agree if you say that doesn't worth that but that becomes a ruby
riddle - is it powerful enough to change behaviour depending on context?
I think it is. Curious how.
Robert Klemme wrote:
> On 03/26/2010 05:11 PM, Marat Kamenschikov wrote:
>> def save(validate = true)
>> @a.save
>> a way to redef a method inside of other class' scope?
> What's wrong with doing
>
> class B
> # something very crazy
> def initialize
> @a = A.new
> end
> def save
> @a.save false
> end
> end
>
> as Jesus suggested? Even if you don't do that you could do
>
> class A
> def initialize(owner = nil)
> @owner = owner
> end
>
> def save
> B === @owner ? "VALID" : "INVALID"
> end
> end
>
> class B
> # something not so crazy
> def initialize
> @a = A.new self
> end
> def save
> @a.save
> end
> end
>
> Note: meta programming magic also makes code harder to read.
>
> Kind regards
>
> robert
--
Posted via http://www.ruby-forum.com/.