在 Ruby 中实现注解

class A
  # code goes here ...
  [cached(max: 5)]
  def add a, b
    p 'you just called me!'
    a + b
  end
end

6.times { A.new.add 3, 5 } # should call twice

class A
  def self.cached max: 1145141919810
    @cached_options = { max: max }
  end

  def self.method_added meth
    return if !@cached_options
    max = @cached_options[:max]
    @cached_options = nil
    old = instance_method(meth)
    cached_results = {}
    define_method meth do |*args|
      x = cached_results[args]
      if !x || x[1] >= max
        cached_results[args] = [old.bind(self).call(*args), 1]
      else
        x[1] += 1; x[0]
      end
    end
  end

  [cached(max: 5)]
  def add a, b
    p 'you just called me!'
    a + b
  end
end

6.times { A.new.add 3, 5 }

类似 gem: sig