Ruby refinements in action

The following code was copied from the article Refinements: Monkeypatching Made Safe: [about.com]

#!/usr/bin/env ruby

module SecondsAgo
  refine Fixnum do
    def seconds
      self  # Durations are seconds, so just self
    end

    def minutes
      self * 60
    end

    def hours
      self * 60 * 60
    end

    def ago
      Time.now - self
    end
  end
end

# Check that the monkeypatch is off
begin
  puts 10.seconds.ago
rescue NoMethodError
  puts "Good, off by default"
end

class Tester
  # Check that the monkeypatch is on
  using SecondsAgo

  def do_test
    puts 10.seconds.ago
    puts 10.minutes.ago
  end
end

# Check that the monkeypatch is still off
begin
  puts 10.seconds.ago
rescue NoMethodError
  puts "Good, still off in file scope"
end

Tester.new.do_test

Tags:
Source:
2359hrs.txt
Published:
20-01-2014 23:59