Class: Cid::Datapackage

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Datapackage

Returns a new instance of Datapackage.



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

def initialize(path)
  @path = path
  begin
    @datapackage = JSON.parse(File.new("#{@path}/datapackage.json").read)
  rescue
    return "No datapackage present!"
  end
end

Instance Attribute Details

#jsonObject

Returns the value of attribute json.



8
9
10
# File 'lib/cid/datapackage.rb', line 8

def json
  @json
end

Instance Method Details

#createObject



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
49
50
51
52
# File 'lib/cid/datapackage.rb', line 19

def create

  paths = Dir.glob("#{@path}/*/")

  paths.each do |path|

    if File.file?("#{path}schema.json")
      schema = JSON.parse(File.new(Dir["#{path}schema.json"][0]).read)
    else
      schema = nil
    end

    Dir["#{path}*.csv"].each do |csv|
      ref = csv.split("/").last(2).join("/")

      schema = schema_for_file(ref, true) rescue nil if schema.nil?

      resource = {
        name: File.basename(csv, ".csv"),
        path: ref,
        format: "csv",
        mediatype: "text/csv",
        bytes: File.size(csv)
      }

      resource[:schema] = { fields: schema["fields"] } unless schema.nil?

      @datapackage["resources"].reject! { |r| r["path"] == ref }
      @datapackage["resources"] << resource
    end
  end

  @json = @datapackage.to_json
end

#publish(token = ) ⇒ Object



59
60
61
62
# File 'lib/cid/datapackage.rb', line 59

def publish(token = ENV['GITHUB_OAUTH_TOKEN'])
  git = Cid::Publish.new(@path, token)
  git.publish
end

#schema_for_file(path, json = false) ⇒ Object



64
65
66
67
68
69
70
71
72
# File 'lib/cid/datapackage.rb', line 64

def schema_for_file(path, json = false)
  begin
    schema = @datapackage["resources"].select { |r| r["path"] == path }.first["schema"]
    return Csvlint::Schema.from_json_table(nil, schema) if json === false
  rescue NoMethodError
    nil
  end
  return schema
end

#writeObject



54
55
56
57
# File 'lib/cid/datapackage.rb', line 54

def write
  self.create if @json.nil?
  File.open("#{@path}/datapackage.json", 'w') { |f| f.write(@json) }
end