Class: Valor::Generator

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

Instance Method Summary collapse

Constructor Details

#initialize(name, raw_data, save_directory = nil) ⇒ Generator

name - Name of the base class raw_data - Either JSON or a Ruby Hash save_directory - If specified, will attempt to auto-save generated classes here.



10
11
12
13
14
15
16
# File 'lib/valor.rb', line 10

def initialize(name, raw_data, save_directory = nil)
  @models = {}
  data = raw_data.is_a?(Hash) ? raw_data : JSON.parse(raw_data)
  @models[name] = reduce_hash(data)

  save_files(save_directory) if save_directory
end

Instance Method Details

#save_files(save_directory = Dir.pwd) ⇒ Object

Saves classes and attributes to individual file classes



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/valor.rb', line 19

def save_files(save_directory = Dir.pwd)
  raise "Invalid Directory!" unless File.directory?(save_directory)

  @models.each_pair { |klass_name, attributes|
    file_name = "#{save_directory}/#{klass_name}.rb"

    unless File.exist?(file_name) # Make sure we're not double writing here
      File.open(file_name, 'w') do |file|
        file.puts "class #{klass_name}"
        file.puts '  include Virtus.model'
        file.puts ''
        attributes.each { |attribute| file.puts "  #{attribute}" }
        file.puts 'end'
      end
    end
  }
end