Module: Csv2rest

Defined in:
lib/csv2rest.rb,
lib/csv2rest/cli.rb,
lib/csv2rest/version.rb

Defined Under Namespace

Classes: CLI

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.generate(csv, schema) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/csv2rest.rb', line 9

def self.generate csv, schema
  base_path = File.dirname(csv)
  t = Csvlint::Csvw::Csv2Json::Csv2Json.new( csv, {}, schema, { :validate => true } )
  json = JSON.parse(t.result)

  h = {}

  # Create individual resources
  json["tables"].each do |table|
    table["row"].each do |object|
      obj = object["describes"][0]
      path = obj["@id"].gsub("#{base_path}/","") # NASTINESS - replace with base URL somehow
      resource_name = obj["@type"].gsub("#{base_path}/","") # NASTINESS - replace with base URL somehow
      # parameterize path
      path = path.split('/').map{|x| URI.decode(x).parameterize}.join('/')
      # Dump metadata we don't want in the JSON representation of the object
      obj.delete("@id")
      obj.delete("@type")
      # Store object
      h[path] = obj
      # Add to object list
      h["#{resource_name}"] ||= []
      h["#{resource_name}"] << {
        "url" => path
      }
      # Add resource to root
      h[""] ||= []
      h[""] << {
        "resource" => resource_name,
        "url" => "#{resource_name}"
      }
    end
  end

  # Easier than checking for duplication as we go
  h[""].uniq!

  # Done
  h
end

.write_json(files, options) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/csv2rest.rb', line 50

def self.write_json files, options
  files.each do |name, content|
    # Index
    name = "index" if name == ""
    # Filename
    filename = name + ".json"
    FileUtils.mkdir_p options[:output_dir]
    Dir.chdir(options[:output_dir]) do
      # Create directories
      FileUtils.mkdir_p File.dirname(filename)
      # Write
      File.write(filename, JSON.pretty_generate(content))
    end
  end
end