-1

I'm doing a coding exercise where I need to read & parse from a JSON file in Ruby however it asks that I should keep the solution open ended in case other file types are used in future. I've coded it specifically for JSON currently but I can't think of a way to do this to cater for other file types without using regex - this again would probably be file type specific though because I'd be looking for the data to be formatted in a specific way.

Does anyone have any ideas on how I could do this to work for multiple different file types?

    json_from_file = File.read("test.json")
    hash = JSON.parse(json_from_file)
Dan
  • 9
  • You could try to identify the file type using daunting like https://stackoverflow.com/questions/4600679/detect-mime-type-of-uploaded-file-in-ruby and then `case` based on it? – Jad Jun 13 '21 at 21:39
  • 1
    This question is way too broad. There are far too many possible designs, and no constraints given that would help choose one. Factories, Strategies, Parser frameworks, they all could be used in some way, shape, or form … or something completely different. – Jörg W Mittag Jun 14 '21 at 04:55
  • Read about factory and strategy pattern. In short, you probably want to have different handlers for different files types, and probably default one which will simply just read file as is without any parsing. – Sergei Sirik Jun 14 '21 at 17:17

1 Answers1

1

I reckon what they want to see is that you have one class to read the file and another class to parse the JSON.

By separating the concerns you would be able to reuse the reader but use another parser class when you have to work with different file types.

Why do I say classes and not methods? First, this question feels like an exercise. Second, reading and parsing is actually more work than a single line of code when you do want to have proper error handling.

spickermann
  • 100,941
  • 9
  • 101
  • 131