Module: Multiplex

Included in:
Net::HTTP
Defined in:
lib/multiplex.rb,
lib/multiplex/version.rb

Overview

Multiplex gently monkey-patches TCPSocket to bind a Net::HTTP request to a non-default local IP address.

If you are craving cURL’s ‘interface` option, this is what you need.

Constant Summary collapse

VERSION =
'0.0.2'

Instance Method Summary collapse

Instance Method Details

#bind(local_ip) ⇒ Object

Binds to a local IP address.

If given a block, unbinds at the end of the block.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/multiplex.rb', line 12

def bind(local_ip)
  (class << TCPSocket; self; end).instance_eval do
    alias_method :original_open, :open
    define_method(:open) do |conn_address, conn_port|
      original_open(conn_address, conn_port, local_ip)
    end
  end

  if block_given?
    begin
      yield
    ensure
      unbind
    end
  end
end

#unbindObject

Unbinds from the local IP address specified in earlier call to ‘bind`.



30
31
32
33
34
35
# File 'lib/multiplex.rb', line 30

def unbind
  (class << TCPSocket; self; end).instance_eval do
    alias_method :open, :original_open
    remove_method :original_open
  end
end