Class: WrapIO::Fake

Inherits:
Object
  • Object
show all
Defined in:
lib/wrapio/fake.rb

Overview

Enables faking of input to STDIN

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ Fake

Note:

Do not create instances of the WrapIO::Fake class. Instead call WrapIO::Fake#input to fake input to STDIN

Returns a new instance of Fake.

Parameters:

  • input (String, Array<String>)

    the input



17
18
19
20
# File 'lib/wrapio/fake.rb', line 17

def initialize(input)
	@data = input
	@length = input.length
end

Class Method Details

.input(value = nil) { ... } ⇒ Object

This is the main action of the WrapIO::Fake class. It passes the given input to $stdin. Pass a single string or an array of strings to it and each time gets is called, a string from that array with be passed to $stdin starting from index 0 and moving to the end.

Parameters:

  • value (String, Array<String>) (defaults to: nil)

    the value of the faked input(s)

Yields:

  • the block of code to which you want to pass the given input(s)



50
51
52
53
54
55
56
57
58
# File 'lib/wrapio/fake.rb', line 50

def self.input(value=nil)
	value = [value] unless value.is_a?(Array)
	begin
		$stdin = new(value)
		yield
	ensure
		$stdin = STDIN
	end
end

Instance Method Details

#getsObject

Provides a proxy for STDIN#gets. When the instance of $stdin is swapped in WrapIO::Fake#input this method with be called instead of the usual STDIN#gets. Allowing injection of faked input.

This function destructively iterates through the @data array injecting the next value into $stdin. Once all indexes in the given data are sent to $stdin, all subsequent calls to gets will receive an empty string.



33
34
35
36
37
38
# File 'lib/wrapio/fake.rb', line 33

def gets
	next_input = @data.shift
	index = @length - @data.length
	WrapIO.log(next_input, :input, index) if WrapIO.debug
	next_input.to_s
end