Skip to content

Instantly share code, notes, and snippets.

@louishuyng
Last active November 11, 2023 07:03
Show Gist options
  • Save louishuyng/b58ed695736f276c35ebb0ec150b1792 to your computer and use it in GitHub Desktop.
Save louishuyng/b58ed695736f276c35ebb0ec150b1792 to your computer and use it in GitHub Desktop.
Ruby Runtime Feature Changes
p = Person.new
p.refresh # => (...)
Person.start_trace
p.refresh # => (...)
# -> refresh: 0.500 s.
Person.end_trace
p.refresh # => (...)
class Person
TIMED_METHODS = [:refresh, :dup]
TIMED_METHODS.each do |method|
# set up _without_timing alias of original method
alias_method :"#{method}_without_timing", method
# set up _with_timing method that wraps the original in timing code
define_method :"#{method}_with_timing" do
start_time = Time.now.to_f
returning(self.send(:"#{method}_without_timing")) do
end_time = Time.now.to_f
puts "#{method}: #{"%.3f" % (end_time-start_time)} s."
end
end
end
end
class Person
def refresh
puts "I am refreshing"
end
def dup
puts "Duplicated"
end
end
class << Person
TIMED_METHODS = [:refresh, :dup]
def start_trace
TIMED_METHODS.each do |method|
alias_method method, :"#{method}_with_timing"
end
end
def end_trace
TIMED_METHODS.each do |method|
alias_method method, :"#{method}_without_timing"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment