Module: GameOfLife::Generators::Input
- Defined in:
- lib/game_of_life/generators/input.rb
Overview
Generate a new Universe/Board from a parsed local file or remote URL/file
Class Method Summary collapse
-
.new(options) ⇒ GameOfLife::Universe
Generate a new Universe/Board from a parsed local file or remote URL/file.
Instance Method Summary collapse
-
#generate_input_data(uri:) ⇒ Array<Array<True|False>>
private
Generate the seeding data for populating the Universe from input URI.
-
#populate(input:, width:, height:) ⇒ GameOfLife::Universe
private
Populate the Universe with reference to the parsed input 2D array (True/False).
Class Method Details
.new(options) ⇒ GameOfLife::Universe
Generate a new Universe/Board from a parsed local file or remote URL/file
19 20 21 22 23 24 25 |
# File 'lib/game_of_life/generators/input.rb', line 19 def new() width = ["width"].to_i height = ["height"].to_i uri = ["input"] input = generate_input_data(uri: uri) populate(input: input, width: width, height: height) end |
Instance Method Details
#generate_input_data(uri:) ⇒ Array<Array<True|False>> (private)
Generate the seeding data for populating the Universe from input URI
31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/game_of_life/generators/input.rb', line 31 private def generate_input_data(uri:) # By design, it's intentional that we use URI.open to to allow seamless file and url access raw = URI.open(uri).read.split("\n") # rubocop:disable Security/Open # Parse the file and convert it to a boolean 2D array # where any alpha numeric character is considered a living cell (true) raw.map! { |row| row.chars.map { |char| char.match?(/[[:alnum:]]/) } } rescue ::OpenURI::HTTPError, ::SocketError raise GameOfLife::Error, "URL isn't avaialable, please check it again and make sure the URL is correct" rescue ::Errno::ENOENT raise GameOfLife::Error, "File isn't avaialable, please check it again and make sure the path to the input file is correct" end |
#populate(input:, width:, height:) ⇒ GameOfLife::Universe (private)
Populate the Universe with reference to the parsed input 2D array (True/False)
51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/game_of_life/generators/input.rb', line 51 private def populate(input:, width:, height:) # Generate a universe based on the parsed raw file and fill it with the cells universe = GameOfLife::Universe.new(height: height, width: width) (0...height).each do |i| (0...width).each do |j| cell = { x: j, y: i, alive: input.fetch(i, nil)&.fetch(j, nil) } universe[i][j] = ::GameOfLife::Cell.new(**cell) end end universe end |