Last active
December 16, 2016 20:54
-
-
Save chrisseto/0939119043e820e6a8fb8e4e254b08c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'set' | |
require 'json' | |
require 'securerandom' | |
module SHAREClient | |
class GraphNode | |
attr_reader :id | |
attr_reader :type | |
attr_reader :attrs | |
attr_reader :relations | |
def initialize(type, **attrs) | |
@id = '_:' + SecureRandom.uuid | |
@type = type | |
@relations = {} | |
@attrs = attrs | |
@attrs.each do |key, value| | |
if value.is_a? GraphNode or value.is_a? Array | |
@relations[key] = value | |
end | |
end | |
end | |
def ref() | |
{'@id': @id, '@type': @type} | |
end | |
def serialize() | |
self.ref.merge(@attrs).merge(Hash[@relations.map {|k, v| | |
if v.is_a? Array | |
[k, v.map {|x| x.ref}] | |
else | |
[k, v.ref] | |
end | |
}]) | |
end | |
def related() | |
@relations.map {|k, v| v}.flatten | |
end | |
end | |
class Graph | |
attr_reader :nodes | |
def initialize(nodes=[]) | |
@nodes = nodes | |
end | |
def serialize() | |
graph = [] | |
visited = Set.new | |
to_visit = Set.new @nodes | |
while not to_visit.empty? | |
node = to_visit.to_a[0] | |
to_visit.delete(node) | |
if visited.include? node | |
next | |
end | |
visited.add(node) | |
to_visit.merge(node.related) | |
graph.push(node.serialize) | |
end | |
{'@graph': graph} | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require './client' | |
require 'net/http' | |
graph = SHAREClient::Graph.new [ | |
SHAREClient::GraphNode.new( | |
'CreativeWork', | |
title: 'All About Cats', | |
identifiers: [ | |
SHAREClient::GraphNode.new('WorkIdentifier', uri: 'http://example.com/cats.cats') | |
] | |
) | |
] | |
uri = URI.parse('http://staging-share.osf.io/api/v2/normalizeddata/') | |
Net::HTTP.start(uri.host, uri.port) do |http| | |
request = Net::HTTP::Post.new uri | |
req['Authorization'] = 'Bearer <YOUR TOKEN>' | |
req.content_type = 'application/vnd.api+json' | |
req.body = { | |
'data': { | |
'type': 'NormalizedData', | |
'attributes': { | |
'data': graph.serialize | |
} | |
} | |
}.to_json | |
http.request request | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment