Skip to content

Commit ef25620

Browse files
committed
feat: send method to writer or reader by define method_missing
1 parent c59a54c commit ef25620

File tree

2 files changed

+28
-51
lines changed

2 files changed

+28
-51
lines changed

lib/rb/io/multi_writer.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ class MultiWriter
1515
# If `#sync_close?` is `true`, closing this `IO` will close all of the underlying
1616
# IOs.
1717
attr_accessor :sync_close
18+
attr_accessor :writers
1819
attr_reader :closed
1920

2021
@closed = false

lib/rb/io/stapled.rb

Lines changed: 27 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ class IO
1515
class Stapled
1616
# If `#sync_close?` is `true`, closing this `IO` will close the underlying `IO`s.
1717
attr_accessor :sync_close
18+
attr_reader :reader
19+
attr_reader :writer
1820

1921
# Returns `true` if this `IO` is closed.
2022
#
@@ -23,6 +25,15 @@ class Stapled
2325

2426
@closed = false
2527

28+
WRITER_DELEGATE = [
29+
:<<
30+
].freeze
31+
32+
READER_DELEGATE = [
33+
:eof,
34+
:eof?
35+
].freeze
36+
2637
alias_method :sync_close?, :sync_close
2738
alias_method :closed?, :closed
2839

@@ -33,53 +44,26 @@ def initialize(reader, writer, sync_close: false)
3344
@sync_close = sync_close
3445
end
3546

36-
def read(...)
37-
check_open
38-
39-
@reader.read(...)
40-
end
41-
42-
def readlines(...)
43-
check_open
44-
45-
@reader.readlines(...)
46-
end
47-
48-
def each_line(...)
49-
check_open
50-
51-
@reader.each_line(...)
52-
end
53-
54-
# Gets a string from `reader`.
55-
def gets(...)
56-
check_open
57-
58-
@reader.gets(...)
59-
end
60-
61-
def puts(...)
62-
check_open
63-
64-
@writer.puts(...)
65-
end
66-
67-
def print(...)
68-
check_open
69-
70-
@writer.print(...)
47+
def method_missing(name, *args, &block) # rubocop:disable Style/MissingRespondToMissing
48+
if write_methods?(name.to_s)
49+
check_open
50+
@writer.send(name, *args, &block)
51+
elsif read_methods?(name.to_s)
52+
check_open
53+
@reader.send(name, *args, &block)
54+
else
55+
super
56+
end
7157
end
7258

73-
def printf(...)
74-
check_open
75-
76-
@writer.print(...)
59+
def write_methods?(name)
60+
name.include?("put") || name.include?("print") || name.include?("write") ||
61+
WRITER_DELEGATE.include?(name)
7762
end
7863

79-
def write(...)
80-
check_open
81-
82-
@writer.write(...)
64+
def read_methods?(name)
65+
name.include?("get") || name.include?("read") || name.include?("each") ||
66+
READER_DELEGATE.include?(name)
8367
end
8468

8569
# Flushes `writer`.
@@ -105,14 +89,6 @@ def close
10589
end
10690
end
10791

108-
def close_write
109-
@writer.close
110-
end
111-
112-
def close_read
113-
@reader.close
114-
end
115-
11692
protected def check_open
11793
raise IOError.new("Closed stream") if closed?
11894
end

0 commit comments

Comments
 (0)