Displaying articles with tag asoby

AOP :: Asoby

Posted by PunNeng, Sat Jun 02 01:15:00 UTC 2007

มาลอง tool ที่ชื่อว่า Asoby หรือ Aspect-Oriented Programming in Ruby กันบ้าง

ผมว่า code มันดูสวยดีนะ การทำ pointcut ก็มีเงื่อนไขเพิ่มขึ้น เพิ่มความสามารถเพิ่มขึ้นจาก AspectR อยู่เยอะเลย
วิธีเล่น(บน Ubuntu) นะครับ

$ wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.5.tar.gz
$ tar zxvf ruby-1.8.5.tar.gz
$ wget http://asoby.redirectme.net/asoby/patch/asoby-0.01-2007.01.23.patch
$ wget http://asoby.redirectme.net/asoby/patch/asoby-0.01-2007.01.23.patch.md5sum
$ md5sum -c asoby-0.01-2007.01.23.patch.md5sum
$ patch -p0 < asoby-0.01-2007.01.23.patch
$ cd ruby-1.8.5
$ ./configure && make
$ gedit logging_test.rb

เอา code มาแปะหน่อย

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
require "aspect"

class Logging < Aspect
  def self.enable!
    super
    @logger = Logger.new
  end

  def self.tick; "#{Time.now.strftime('%Y-%m-%d %X')}"; end   

  pointcut(:log) { call(Product.setPrice($p)) }
  before(:log) { @logger.writeLog("#{context.self_obj.price} is changed to #{$p}") }
  after(:log) { @logger.writeLog("#{tick} #{context.class_name}##{context.method_name}: returned #{context.retval} and exited") }
end

class Product
  attr_reader :price
  def initialize
    @price = 0.0
    # logger = Logger.new
  end

  def setPrice(p)
    # @logger.writeLog("#{price} is changed to #{p}")
    @price = p
  end
end

class Logger  
  def initialize  
    # open log file  
  end  

  def writeLog(msg)  
    # write msg to log file  
    puts msg  
  end  
end  


Logging.enable!
product = Product.new
product.setPrice(13)  
product.setPrice(12)

สั่ง save แล้วรัน

$ ./ruby --weave logging_test.rb

มาดูผล

ข้อมูลจาก link ข้างบนนั่นแหละ

0 comments | Filed Under: Ruby | Tags: asoby

codegent: we're hiring