Skip to content

TCPSocket.openも書き換えたほうがいい #2

Closed
@edvakf

Description

#1 対応ありがとうございます。

関連してもう一つお願いしたいことがあります。TCPSocket.open は親の親の親のクラスの IO.open にたどり着くのですが、rb_class_new_instance っていうのでインスタンスが作られるので new メソッドを通らないっぽいです。

static VALUE
rb_io_s_open(int argc, VALUE *argv, VALUE klass)
{
    VALUE io = rb_class_new_instance(argc, argv, klass);

    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, io, io_close, io);
    }

    return io;
}

open もモンキーパッチしました。

diff --git a/lib/unix_socket_hack.rb b/lib/unix_socket_hack.rb
index f38b35b..51e913b 100644
--- a/lib/unix_socket_hack.rb
+++ b/lib/unix_socket_hack.rb
@@ -11,6 +11,7 @@ class UNIXSocketHack
   def self.apply(mapping)
     TCPSocket.singleton_class.class_eval do
       alias_method :new_without_unixsockhack, :new
+      alias_method :new_without_unixsockhack, :open

       define_method(:new_with_unixsockhack) do |remote_host, remote_port, local_host=nil, local_port=nil|
         if val = mapping[[remote_host, remote_port].join(":")]
@@ -29,6 +30,7 @@ class UNIXSocketHack
       end

       alias_method :new, :new_with_unixsockhack
+      alias_method :open, :new_with_unixsockhack
     end

     UNIXSocket.class_eval do
diff --git a/spec/unix_socket_hack_spec.rb b/spec/unix_socket_hack_spec.rb
index e75813c..33fd163 100644
--- a/spec/unix_socket_hack_spec.rb
+++ b/spec/unix_socket_hack_spec.rb
@@ -20,15 +20,21 @@ describe "UnixSocketHack" do
   it "connect to unixsocket:9999 should be UNIXSock" do 
     sock = TCPSocket.new('localhost', 9999);
     sock.class.should == UNIXSocket
+    sock = TCPSocket.open('localhost', 9999);
+    sock.class.should == UNIXSocket
   end

   it "connect to localhost:9998 should be TCPSocket" do 
     sock = TCPSocket.new('localhost', 9998);
     sock.class.should == TCPSocket
+    sock = TCPSocket.open('localhost', 9998);
+    sock.class.should == TCPSocket
   end

   it "connect to 127.0.0.1:9999 should be TCPSocket" do 
     sock = TCPSocket.new('127.0.0.1', 9999);
     sock.class.should == TCPSocket
+    sock = TCPSocket.open('127.0.0.1', 9999);
+    sock.class.should == TCPSocket
   end
 end

具体的な例では、Net::HTTP が TCPSocket.open を使っているので、それを UNIXSocket を使うようにしたいです。

Ruby の lib/net/http.rb

    def connect
      if proxy? then
        conn_address = proxy_address
        conn_port    = proxy_port
      else
        conn_address = address
        conn_port    = port
      end

      D "opening connection to #{conn_address}:#{conn_port}..."
      s = Timeout.timeout(@open_timeout, Net::OpenTimeout) {
        TCPSocket.open(conn_address, conn_port, @local_host, @local_port)
      }
      D "opened"

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions