Class: Ru::Stream

Inherits:
Object
  • Object
show all
Defined in:
lib/ru/stream.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stream) ⇒ Stream

Returns a new instance of Stream.

Parameters:

Raises:

  • (ArgumentError)


50
51
52
53
# File 'lib/ru/stream.rb', line 50

def initialize(stream)
  raise ArgumentError unless stream.kind_of? Enumerator::Lazy
  @stream = stream
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object (private)



117
118
119
120
121
122
123
124
125
126
# File 'lib/ru/stream.rb', line 117

def method_missing(method, *args, &block)
  result = @stream.send(method, *args, &block)
  if result.kind_of? Enumerator::Lazy
    self.class.new(result)
  elsif result.kind_of? ::Array
    Ru::Array.new(result)
  else
    result
  end
end

Instance Attribute Details

#streamObject (readonly)

Returns the value of attribute stream.



47
48
49
# File 'lib/ru/stream.rb', line 47

def stream
  @stream
end

Instance Method Details

#==(other) ⇒ Object



111
112
113
# File 'lib/ru/stream.rb', line 111

def ==(other)
  other.is_a?(self.class) && self.stream == other.stream
end

#each_lineObject



55
56
57
# File 'lib/ru/stream.rb', line 55

def each_line
  Ru::Iterator.new(self)
end

#filesObject



59
60
61
# File 'lib/ru/stream.rb', line 59

def files
  self.class.new @stream.map { |line| Ru::File.new(line) }
end

#format(format = 'l') ⇒ Object



63
64
65
# File 'lib/ru/stream.rb', line 63

def format(format='l')
  self.class.new @stream.map { |item| item.format(format) }
end

#grep(pattern) ⇒ Object



67
68
69
70
71
72
# File 'lib/ru/stream.rb', line 67

def grep(pattern)
  if pattern.kind_of? String
    pattern = Regexp.new(pattern)
  end
  self.class.new @stream.select { |item| item.to_s =~ pattern }
end

#map(method = nil, *args, &block) ⇒ Object



74
75
76
77
78
79
80
81
82
# File 'lib/ru/stream.rb', line 74

def map(method=nil, *args, &block)
  if method.nil? && !block_given?
    each_line
  elsif method.nil?
    self.class.new @stream.map(&block)
  else
    self.class.new @stream.map { |item| item.send(method, *args) }
  end
end

#select(*args, &block) ⇒ Object



84
85
86
# File 'lib/ru/stream.rb', line 84

def select(*args, &block)
  self.class.new @stream.select(*args, &block)
end

#to_aObject Also known as: to_ary



88
89
90
# File 'lib/ru/stream.rb', line 88

def to_a
  Ru::Array.new(@stream.to_a)
end

#to_sObject



94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/ru/stream.rb', line 94

def to_s
  result = ''
  result.concat @stream.next.to_s
  loop do
    item = @stream.next.to_s
    result.concat "\n".freeze
    result.concat item
  end
  result
rescue StopIteration
  result
end

#to_selfObject



107
108
109
# File 'lib/ru/stream.rb', line 107

def to_self
  self
end