Class: Levels::Setup::Input
- Inherits:
-
Object
- Object
- Levels::Setup::Input
- Defined in:
- lib/levels/setup.rb
Overview
This class transforms any supported object into Level data. The object can be any of:
* A file path to Ruby, JSON or YAML
* Ruby, JSON or YAML code
* An object that responds to `#read(level)`.
Instance Method Summary collapse
-
#identify ⇒ Object
Determine the format of the source and read it from disk if it’s a file.
-
#initialize(source) ⇒ Input
constructor
A new instance of Input.
-
#input ⇒ Object
Returns a Levels::Input.
-
#read(level) ⇒ Object
Read the input into a Level.
Constructor Details
#initialize(source) ⇒ Input
84 85 86 |
# File 'lib/levels/setup.rb', line 84 def initialize(source) @source = source end |
Instance Method Details
#identify ⇒ Object
Determine the format of the source and read it from disk if it’s a file.
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/levels/setup.rb', line 109 def identify if @source.respond_to?(:read) return :custom, @source end pn = Pathname.new(@source) if pn.exist? case pn.extname when ".rb" then [:ruby, pn.read, pn.to_s, 1] when ".json" then [:json, pn.read] when ".yaml", ".yml" then [:yaml, pn.read] else raise ArgumentError, "Could not identify the file type: #{pn.extname}" end else case @source when /\A\w*{/ then [:json, @source] when /\A---$/ then [:yaml, @source] when /\A\w*group/ then [:ruby, @source, "Code from String", 1] else raise ArgumentError, "Could not identify the source: #{@source.inspect}" end end end |
#input ⇒ Object
Returns a Levels::Input. Raises an ArgumentError if the format couldn’t be determined.
96 97 98 99 100 101 102 103 104 105 |
# File 'lib/levels/setup.rb', line 96 def input format, source, *args = identify case format when :custom then source when :ruby then Levels::Input::Ruby.new(source, *args) when :json then Levels::Input::JSON.new(source) when :yaml then Levels::Input::YAML.new(source) else raise ArgumentError, "Could not identify the format: #{format.inspect}" end end |
#read(level) ⇒ Object
Read the input into a Level. Raises an ArgumentError if the source cannot be used as an input.
90 91 92 |
# File 'lib/levels/setup.rb', line 90 def read(level) input.read(level) end |