2

I'm trying to refine 'get' method inside HTTP class with no success.
I anticipate to get 'HTTP#get in Faker" in output; but the program runs the original 'get' method inside Net::HTTP.
Are we allowed to do the following code in Ruby 2.1?

require 'net/http'
module Faker
  refine Net::HTTP do
    def self.get(dummy)
      puts "HTTP#get in Faker"
    end
  end
end

using Faker
uri = URI('http://www.google.com')
x = Net::HTTP.get(uri)
Dave Qorashi
  • 326
  • 2
  • 11
  • refinements are *not* supposed to be applied on class methods, see [this](http://stackoverflow.com/questions/15220526/are-refinements-in-ruby-2-0-totally-useless) question – mdemolin Feb 24 '14 at 05:04
  • ok, this explains my problem then. Thank you – Dave Qorashi Feb 24 '14 at 05:39

2 Answers2

1

Class method can be refined via singleton_class of the class you would like to refine:

require 'net/http'

module Faker
  refine Net::HTTP.singleton_class do
    def get(dummy)
      puts "HTTP#get in Faker"
    end
  end
end

using Faker
uri = URI('http://www.google.com')
x = Net::HTTP.get(uri)
Jakub Jirutka
  • 10,269
  • 4
  • 42
  • 35
0

I found the solution to my problem.
We can refine class methods using this trick:

Here, it is:

require 'net/http'
include Net
module Faker
  refine Class do
    def HTTP.get(dummy)
      puts "HTTP#get in M"
    end
  end
end

using Faker
uri = URI('http://www.google.com')
x = HTTP.get(uri)
Dave Qorashi
  • 326
  • 2
  • 11