Class: DataFiles::REPL
- Inherits:
-
Object
- Object
- DataFiles::REPL
- Defined in:
- lib/data_files/repl.rb
Overview
Loads all yaml files in given directory, creates ActiveData subclass for each file and provides an interactive shell.
Instance Method Summary collapse
- #create_class(klass_name, data) ⇒ Object
- #initial_prompt ⇒ Object
-
#initialize(directory) ⇒ REPL
constructor
A new instance of REPL.
- #parse_data(directory) ⇒ Object
- #prompt ⇒ Object
- #read_input ⇒ Object
Constructor Details
#initialize(directory) ⇒ REPL
Returns a new instance of REPL.
13 14 15 16 |
# File 'lib/data_files/repl.rb', line 13 def initialize(directory) @klass_names = [] parse_data(directory) end |
Instance Method Details
#create_class(klass_name, data) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/data_files/repl.rb', line 31 def create_class(klass_name, data) @klass_names << klass_name types = parse_types(data) klass = Class.new(ActiveData) do class_variable_set(:@@data, data) class_variable_set(:@@attributes, data.first.keys) class_variable_set(:@@types, types) attr_accessor(*data.first.keys) end Object.const_set(klass_name, klass) end |
#initial_prompt ⇒ Object
51 52 53 54 55 56 |
# File 'lib/data_files/repl.rb', line 51 def initial_prompt puts 'Available data models:' @klass_names.sort.each do |klass_name| puts " - #{klass_name}" end end |
#parse_data(directory) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/data_files/repl.rb', line 18 def parse_data(directory) Dir.foreach(File.join(directory, 'data')) do |filename| next unless filename.end_with?('.yml') filepath = File.join(directory, 'data', filename) key = File.basename(filepath, File.extname(filepath)) data = load_yaml(filepath) klass_name = key.capitalize.delete_suffix('s') create_class(klass_name, data) end end |
#prompt ⇒ Object
45 46 47 48 49 |
# File 'lib/data_files/repl.rb', line 45 def prompt initial_prompt DataFiles::Autocompletion.new read_input end |
#read_input ⇒ Object
58 59 60 61 62 63 64 65 66 67 |
# File 'lib/data_files/repl.rb', line 58 def read_input bnd = binding while (input = Readline.readline('> ', true)) begin puts bnd.eval(input).to_s rescue StandardError => e puts "\e[31m#{e.class}:\e[0m #{e.message}" end end end |