Class: DataFiles::REPL

Inherits:
Object
  • Object
show all
Defined in:
lib/data_files/repl.rb

Instance Method Summary collapse

Constructor Details

#initialize(directory) ⇒ REPL

Returns a new instance of REPL.



12
13
14
15
# File 'lib/data_files/repl.rb', line 12

def initialize(directory)
  @klass_names = []
  parse_data(directory)
end

Instance Method Details

#create_class(klass_name, data) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/data_files/repl.rb', line 30

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_promptObject



49
50
51
52
53
54
# File 'lib/data_files/repl.rb', line 49

def initial_prompt
  puts 'Available data models:'
  @klass_names.sort.each do |klass_name|
    puts " - #{klass_name}"
  end
end

#parse_data(directory) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/data_files/repl.rb', line 17

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

#promptObject



44
45
46
47
# File 'lib/data_files/repl.rb', line 44

def prompt
  initial_prompt
  read_input
end

#read_inputObject



56
57
58
59
60
61
62
63
64
65
# File 'lib/data_files/repl.rb', line 56

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