Skip to content

Instantly share code, notes, and snippets.

@mgiagante
Last active October 13, 2016 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgiagante/b84b64dd51d2d77905650b84b708f799 to your computer and use it in GitHub Desktop.
Save mgiagante/b84b64dd51d2d77905650b84b708f799 to your computer and use it in GitHub Desktop.
# TODO: Cómo hago que funcione con métodos que reciben parámetros?
# Referencia: http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/
module Countable
module ClassMethods
def count_invocations_of(sym)
alias_method "original_#{sym}".to_sym, sym
define_method(sym) do
start_counter
@invocations[sym] += 1
send("original_#{sym}")
end
end
end
# Module#included hook
def self.included(includer)
includer.extend(ClassMethods)
end
def invoked?(sym)
start_counter
@invocations[sym] > 0
end
def invoked(sym)
start_counter
@invocations[sym]
end
private
def start_counter
@invocations ||= Hash.new(0)
end
end
# Ejemplo de uso de Countable
class Greeter
# Incluyo el Mixin
include Countable
def hi
puts 'Hey!'
end
def bye
puts 'See you!'
end
# Indico que quiero llevar la cuenta de veces que se invoca el método #hi
count_invocations_of :hi
end
a = Greeter.new
b = Greeter.new
a.invoked? :hi
# => false
b.invoked? :hi
# => false
a.hi
# Imprime "Hey!"
a.invoked :hi
# => 1
b.invoked :hi
# => 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment