🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: pl.comp.lang.ruby
Article #186

Re: Ruby i dekorator

#186
From: Marcin Mielżyński
Date: Thu, 07 Sep 2006 12:59
59 lines
2191 bytes
Jaroslaw Zabiello wrote:
> Dnia Thu, 07 Sep 2006 13:42:42 +0200, Marcin Mielżyński napisał(a):

> method_added() wyłapuje fakt dodania metody, więc po co mi to? alias nie
> potrzebuję, bo chcę zachować tą samą nazwę. A define_method tworzy a nie
> odczytuje ciało metody.

method_added będzie bardzo przydatne dla zbliżenia do pythonowej wersji,
method_alias i define_method - koniecznie - no chyba chyba że przez 
undef_method.

podstawy w bardzo prosty sposób można zrobić tak (dwie wersje):

class Class

     def around meth,pre,post
         alias_method :"old_#{meth}",meth.to_sym
         define_method meth do
             pre.call
             send :"old_#{meth}"
             post.call
         end
     end

     def around2 meth
         alias_method :"old_#{meth}",meth.to_sym
         define_method meth do
             yield method(:"old_#{meth}").to_proc
         end
     end

end

class A
     def meth
         p "meth"
     end

     def meth2
         p "meth2"
     end
end

A.around :meth, proc{p "pre"},proc{p "post"}
A.new.meth

A.around2 :meth2 do |m|
     p "pre2"
     m.call
     p "post2"
end

A.new.meth2


łatwo przerobić na dużo wygodniejsze użycie...


lopex
Technical Details
Message-ID: <edp53n$b6v$1@news.onet.pl>
Path: mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!newsfeed.gazeta.pl!news.onet.pl!not-for-mail
References: <re7vnvdwaxef.1xsf47isecttl$.dlg@40tude.net> <edp0jp$ph2$1@news.onet.pl> <1b5oye9z0x1aq.n67fdxozbl7i.dlg@40tude.net>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!newsfeed.gazeta.pl!news.onet.pl!not-for-mail
From: Marcin Mielżyński <lopx@gazeta.pl>
Newsgroups: pl.comp.lang.ruby
Subject: Re: Ruby i dekorator
Date: Thu, 07 Sep 2006 14:59:22 +0200
Organization: Onet.pl
Lines: 59
Message-ID: <edp53n$b6v$1@news.onet.pl>
References: <re7vnvdwaxef.1xsf47isecttl$.dlg@40tude.net> <edp0jp$ph2$1@news.onet.pl> <1b5oye9z0x1aq.n67fdxozbl7i.dlg@40tude.net>
NNTP-Posting-Host: cuo178.internetdsl.tpnet.pl
Mime-Version: 1.0
X-Trace: news.onet.pl 1157633975 11487 83.19.70.178 (7 Sep 2006 12:59:35 GMT)
X-Complaints-To: usenet@news.onet.pl
NNTP-Posting-Date: Thu, 7 Sep 2006 12:59:35 +0000 (UTC)
X-Sender: 5Da2qcG7AWj7WISFX859Php/OS6q4VnB
In-Reply-To: <1b5oye9z0x1aq.n67fdxozbl7i.dlg@40tude.net>
User-Agent: Thunderbird 1.5.0.5 (Windows/20060719)
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit