Method: Open4.relay

Defined in:
lib/crazy_ivan/vendor/open4-1.0.1/lib/open4.rb

.relay(src, dst = nil, t = nil) ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/crazy_ivan/vendor/open4-1.0.1/lib/open4.rb', line 198

def relay src, dst = nil, t = nil
#--{{{
  send_dst =
    if dst.respond_to?(:call)
      lambda{|buf| dst.call(buf)}
    else
      lambda{|buf| dst << buf}
    end

  unless src.nil?
    if src.respond_to? :gets
      while buf = to(t){ src.gets }
        send_dst[buf]
      end

    elsif src.respond_to? :each
      q = Queue.new
      th = nil

      timer_set = lambda do |t|
        th = new_thread{ to(t){ q.pop } }
      end

      timer_cancel = lambda do |t|
        th.kill if th rescue nil
      end

      timer_set[t]
      begin
        src.each do |buf|
          timer_cancel[t]
          send_dst[buf]
          timer_set[t]
        end
      ensure
        timer_cancel[t]
      end

    elsif src.respond_to? :read
      buf = to(t){ src.read }
      send_dst[buf]

    else
      buf = to(t){ src.to_s }
      send_dst[buf]
    end
  end
#--}}}
end