Class: Panier::Application::InputReader
- Inherits:
-
Object
- Object
- Panier::Application::InputReader
- Defined in:
- lib/panier/application/input_reader.rb
Overview
The InputReader is responsible for parsing raw input data.
Constant Summary collapse
- CELLS_PER_LINE =
3- HEADER =
/quantity.*?,.*?product.*?,.*?price/i
Instance Method Summary collapse
-
#initialize(product_service = nil) ⇒ InputReader
constructor
A new instance of InputReader.
- #parse_input(input) ⇒ Object
- #parse_line(line) ⇒ Object
Constructor Details
#initialize(product_service = nil) ⇒ InputReader
Returns a new instance of InputReader.
14 15 16 17 |
# File 'lib/panier/application/input_reader.rb', line 14 def initialize(product_service = nil) @product_service = product_service || Panier::Domain::ProductService.new end |
Instance Method Details
#parse_input(input) ⇒ Object
19 20 21 22 23 24 |
# File 'lib/panier/application/input_reader.rb', line 19 def parse_input(input) line_items = input.lines.reject(&:blank?).map do |line| parse_line(line) end line_items.reject(&:nil?) end |
#parse_line(line) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/panier/application/input_reader.rb', line 26 def parse_line(line) return nil if line.match(HEADER) parsed = CSV.parse_line(line) unless parsed.count == CELLS_PER_LINE fail ArgumentError, 'invalid input' end quantity = Integer(parsed[0]) name = parsed[1].strip price = Money.new(Float(parsed[2]) * 100) product = @product_service.find_by_name_and_price(name, price) product.present? ? LineItem.new(product, quantity) : nil end |