sawyer 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source "http://rubygems.org"
2
+
3
+ gemspec
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2011 rick olson
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,17 @@
1
+ # Sawyer
2
+
3
+ Sawyer is an experimental secret user agent built on top of
4
+ [Faraday][faraday].
5
+
6
+ ![](http://techno-weenie.net/sawyer/images/faraday.jpeg)
7
+
8
+ Think of Faraday as the nerdy scientist behind an HTTP API. Sure, he
9
+ knows the technical details of how to communicate with an application.
10
+ But he also gets overly obsessive about alternate timelines to be of
11
+ much use.
12
+
13
+ ![](http://techno-weenie.net/sawyer/images/sawyer.jpeg)
14
+
15
+ Sawyer knows what needs to be done. He gets in there, assesses the
16
+ situation, and figures out the next action.
17
+
@@ -0,0 +1,135 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'date'
4
+
5
+ #############################################################################
6
+ #
7
+ # Helper functions
8
+ #
9
+ #############################################################################
10
+
11
+ def name
12
+ @name ||= Dir['*.gemspec'].first.split('.').first
13
+ end
14
+
15
+ def version
16
+ line = File.read("lib/#{name}.rb")[/^\s*VERSION\s*=\s*.*/]
17
+ line.match(/.*VERSION\s*=\s*['"](.*)['"]/)[1]
18
+ end
19
+
20
+ def date
21
+ Date.today.to_s
22
+ end
23
+
24
+ def rubyforge_project
25
+ name
26
+ end
27
+
28
+ def gemspec_file
29
+ "#{name}.gemspec"
30
+ end
31
+
32
+ def gem_file
33
+ "#{name}-#{version}.gem"
34
+ end
35
+
36
+ def replace_header(head, header_name)
37
+ head.sub!(/(\.#{header_name}\s*= ').*'/) { "#{$1}#{send(header_name)}'"}
38
+ end
39
+
40
+ #############################################################################
41
+ #
42
+ # Standard tasks
43
+ #
44
+ #############################################################################
45
+
46
+ task :default => :test
47
+
48
+ require 'rake/testtask'
49
+ Rake::TestTask.new(:test) do |test|
50
+ test.libs << 'lib' << 'test'
51
+ test.pattern = 'test/**/*_test.rb'
52
+ test.verbose = true
53
+ end
54
+
55
+ desc "Open an irb session preloaded with this library"
56
+ task :console do
57
+ sh "irb -rubygems -r ./lib/#{name}.rb"
58
+ end
59
+
60
+ #############################################################################
61
+ #
62
+ # Custom tasks (add your own tasks here)
63
+ #
64
+ #############################################################################
65
+
66
+
67
+
68
+ #############################################################################
69
+ #
70
+ # Packaging tasks
71
+ #
72
+ #############################################################################
73
+
74
+ desc "Create tag v#{version} and build and push #{gem_file} to Rubygems"
75
+ task :release => :build do
76
+ unless `git branch` =~ /^\* master$/
77
+ puts "You must be on the master branch to release!"
78
+ exit!
79
+ end
80
+ sh "git commit --allow-empty -a -m 'Release #{version}'"
81
+ sh "git tag v#{version}"
82
+ sh "git push origin master"
83
+ sh "git push origin v#{version}"
84
+ sh "gem push pkg/#{name}-#{version}.gem"
85
+ end
86
+
87
+ desc "Build #{gem_file} into the pkg directory"
88
+ task :build => :gemspec do
89
+ sh "mkdir -p pkg"
90
+ sh "gem build #{gemspec_file}"
91
+ sh "mv #{gem_file} pkg"
92
+ end
93
+
94
+ desc "Generate #{gemspec_file}"
95
+ task :gemspec => :validate do
96
+ # read spec file and split out manifest section
97
+ spec = File.read(gemspec_file)
98
+ head, manifest, tail = spec.split(" # = MANIFEST =\n")
99
+
100
+ # replace name version and date
101
+ replace_header(head, :name)
102
+ replace_header(head, :version)
103
+ replace_header(head, :date)
104
+ #comment this out if your rubyforge_project has a different name
105
+ replace_header(head, :rubyforge_project)
106
+
107
+ # determine file list from git ls-files
108
+ files = `git ls-files`.
109
+ split("\n").
110
+ sort.
111
+ reject { |file| file =~ /^\./ }.
112
+ reject { |file| file =~ /^(rdoc|pkg)/ }.
113
+ map { |file| " #{file}" }.
114
+ join("\n")
115
+
116
+ # piece file back together and write
117
+ manifest = " s.files = %w[\n#{files}\n ]\n"
118
+ spec = [head, manifest, tail].join(" # = MANIFEST =\n")
119
+ File.open(gemspec_file, 'w') { |io| io.write(spec) }
120
+ puts "Updated #{gemspec_file}"
121
+ end
122
+
123
+ desc "Validate #{gemspec_file}"
124
+ task :validate do
125
+ libfiles = Dir['lib/*'] - ["lib/#{name}.rb", "lib/#{name}"]
126
+ unless libfiles.empty?
127
+ puts "Directory `lib` should only contain a `#{name}.rb` file and `#{name}` dir."
128
+ exit!
129
+ end
130
+ unless Dir['VERSION*'].empty?
131
+ puts "A `VERSION` file at root level violates Gem best practices."
132
+ exit!
133
+ end
134
+ end
135
+
data/SPEC.md ADDED
@@ -0,0 +1,71 @@
1
+ # Sawyer
2
+
3
+ To use Sawyer, create a new Agent with a URL endpoint.
4
+
5
+ ```ruby
6
+ endpoint = "http://my-api.com"
7
+ agent = Sawyer::Agent.new endpoint do |conn|
8
+ conn.headers['content-type'] = 'application/vnd.my-api+json'
9
+ end
10
+ ```
11
+
12
+ From here, we can access the root to get the initial actions.
13
+
14
+ ```ruby
15
+ root = agent.start
16
+ ```
17
+
18
+ Every request in Sawyer returns a Sawyer::Response. It's very similar
19
+ to a raw Faraday::Response, with a few extra methods.
20
+
21
+ ```ruby
22
+ # HTTP Headers
23
+ root.headers
24
+
25
+ # HTTP status
26
+ root.status
27
+
28
+ # The JSON Schema
29
+ root.schema
30
+
31
+ # The link relations
32
+ root.rels
33
+
34
+ # The contents (probably empty from the root)
35
+ root.data
36
+ ```
37
+
38
+ Now, we can access a relation off the root resource.
39
+
40
+ ```ruby
41
+ resource = root.data
42
+ res = resource.rels[:users].call :query => {:sort => 'login'}
43
+
44
+ # An array of users
45
+ users = res.data
46
+ ```
47
+
48
+ This call returns two types of relations: relations on the collection of
49
+ users, and relations on each user. You can access the collection
50
+ resources from the response.
51
+
52
+ ```ruby
53
+ # get the next page of users
54
+ res2 = res.rels[:next].call
55
+
56
+ # page 2 of the users collection
57
+ res2.data
58
+ ```
59
+
60
+ Each user has it's own relations too:
61
+
62
+ ```ruby
63
+ # favorite the previous user
64
+ users.each_with_index do |user, index|
65
+ res = user.rels[:favorite].call users[index-1]
66
+ if !res.success?
67
+ puts "#{user.name} could not favorite #{users[index-1].name}"
68
+ end
69
+ end
70
+ ```
71
+
@@ -0,0 +1,50 @@
1
+ require File.expand_path("../../lib/sawyer", __FILE__)
2
+ require 'faraday'
3
+ require 'pp'
4
+
5
+ endpoint = "http://localhost:9393/"
6
+ agent = Sawyer::Agent.new(endpoint) do |http|
7
+ http.headers['content-type'] = 'application/json'
8
+ end
9
+ puts agent.inspect
10
+ puts
11
+
12
+ root = agent.start
13
+ puts root.inspect
14
+
15
+ puts "LISTING USERS"
16
+ users_rel = root.data.rels[:users]
17
+
18
+ puts users_rel.inspect
19
+ puts
20
+
21
+ users_res = users_rel.get
22
+ puts users_res.inspect
23
+
24
+ users = users_res.data
25
+
26
+ users.each do |user|
27
+ puts "#{user.login} favorites:"
28
+
29
+ fav_res = user.rels[:favorites].get
30
+
31
+ fav_res.data.each do |sushi|
32
+ puts "- #{sushi.inspect})"
33
+ end
34
+ puts
35
+ end
36
+
37
+ puts "CREATING USER"
38
+ create_user_rel = root.data.rels[:users]
39
+
40
+ puts create_user_rel.inspect
41
+
42
+ created = create_user_rel.post(:login => 'booya')
43
+ puts created.inspect
44
+ puts
45
+
46
+ puts "ADD A FAVORITE"
47
+ created_user = created.data
48
+ create_fav_res = created_user.rels[:favorites].post nil, :query => {:id => 1}
49
+ puts create_fav_res.inspect
50
+
@@ -0,0 +1,47 @@
1
+ {
2
+ "type": "object",
3
+ "relations": [
4
+ {"rel": "all", "href": "/nigiri"}
5
+ ],
6
+ "properties": {
7
+ "id": {
8
+ "type": "integer",
9
+ "minimum": 1,
10
+ "readonly": true
11
+ },
12
+ "name": {
13
+ "type": "string"
14
+ },
15
+ "fish": {
16
+ "type": "string"
17
+ },
18
+ "_links": {
19
+ "type": "array",
20
+ "items": {
21
+ "type": "object",
22
+ "properties": {
23
+ "rel": {
24
+ "type": "string"
25
+ },
26
+ "href": {
27
+ "type": "string",
28
+ "optional": true
29
+ },
30
+ "method": {
31
+ "type": "string",
32
+ "default": "get"
33
+ },
34
+ "schema": {
35
+ "type": "string",
36
+ "optional": true
37
+ }
38
+ },
39
+ "additionalProperties": false
40
+ },
41
+ "additionalProperties": false,
42
+ "readonly": true
43
+ }
44
+ }
45
+ }
46
+
47
+
@@ -0,0 +1,114 @@
1
+ require 'sinatra'
2
+ require 'yajl'
3
+
4
+ get '/' do
5
+ app_type
6
+
7
+ Yajl.dump({
8
+ :_links => {
9
+ :users => {:href => "/users", :method => 'get,post'},
10
+ :nigiri => {:href => "/nigiri"}
11
+ }
12
+ }, :pretty => true)
13
+ end
14
+
15
+ def app_type
16
+ content_type "application/vnd.sushihub+json"
17
+ end
18
+
19
+ users = [
20
+ {:id => 1, :login => 'sawyer', :created_at => Time.utc(2004, 9, 22),
21
+ :_links => {
22
+ :self => {:href => '/users/sawyer'},
23
+ :favorites => {:href => '/users/sawyer/favorites', :method => 'get,post'}
24
+ }},
25
+ {:id => 2, :login => 'faraday', :created_at => Time.utc(2004, 12, 22),
26
+ :_links => {
27
+ :self => {:href => '/users/faraday'},
28
+ :favorites => {:href => '/users/faraday/favorites', :method => 'get,post'}
29
+ }}
30
+ ]
31
+
32
+ nigiri = [
33
+ {:id => 1, :name => 'sake', :fish => 'salmon',
34
+ :_links => {
35
+ :self => {:href => '/nigiri/sake'}
36
+ }},
37
+ {:id => 2, :name => 'unagi', :fish => 'eel',
38
+ :_links => {
39
+ :self => {:href => '/nigiri/unagi'}
40
+ }}
41
+ ]
42
+
43
+ get '/users' do
44
+ app_type
45
+
46
+ Yajl.dump users, :pretty => true
47
+ end
48
+
49
+ new_users = {}
50
+ post '/users' do
51
+ if env['CONTENT_TYPE'].to_s !~ /json/i
52
+ halt 400, "Needs JSON"
53
+ end
54
+
55
+ app_type
56
+
57
+ hash = Yajl.load request.body.read, :symbolize_keys => true
58
+ new_users[hash[:login]] = hash
59
+
60
+ headers "Location" => "/users/#{hash[:login]}"
61
+ status 201
62
+ Yajl.dump hash.update(
63
+ :id => 3,
64
+ :created_at => Time.now.utc.xmlschema,
65
+ :_links => {
66
+ :self => {:href => "/users/#{hash[:login]}"},
67
+ :favorites => {:href => "/users/#{hash[:login]}/favorites", :method => 'get,post'}
68
+ }
69
+ ), :pretty => true
70
+ end
71
+
72
+ get '/users/:login' do
73
+ headers 'Content-Type' => app_type
74
+ if hash = users.detect { |u| u[:login] == params[:login] }
75
+ Yajl.dump hash, :pretty => true
76
+ else
77
+ halt 404
78
+ end
79
+ end
80
+
81
+ get '/users/:login/favorites' do
82
+ app_type
83
+
84
+ case params[:login]
85
+ when users[0][:login] then Yajl.dump([nigiri[0]], :pretty => true)
86
+ when users[1][:login] then Yajl.dump([], :pretty => true)
87
+ else halt 404
88
+ end
89
+ end
90
+
91
+ post '/users/:login/favorites' do
92
+ if params[:id].to_i > 0
93
+ halt 201
94
+ else
95
+ halt 422
96
+ end
97
+ end
98
+
99
+ get '/nigiri' do
100
+ app_type
101
+
102
+ Yajl.dump nigiri, :pretty => true
103
+ end
104
+
105
+ get '/nigiri/:name' do
106
+ app_type
107
+
108
+ if hash = nigiri.detect { |n| n[:name] == params[:name] }
109
+ Yajl.dump hash, :pretty => true
110
+ else
111
+ halt(404)
112
+ end
113
+ end
114
+