jellyfish 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/.gitmodules ADDED
@@ -0,0 +1,3 @@
1
+ [submodule "task"]
2
+ path = task
3
+ url = git://github.com/godfat/gemgem.git
data/.travis.yml ADDED
@@ -0,0 +1,10 @@
1
+ before_install: 'git submodule update --init'
2
+ script: 'ruby -r bundler/setup -S rake test'
3
+
4
+ env:
5
+ - 'RBXOPT=-X19'
6
+
7
+ rvm:
8
+ - 1.9.3
9
+ - rbx-head
10
+ - jruby-head
data/CHANGES.md ADDED
@@ -0,0 +1,5 @@
1
+ # CHANGES
2
+
3
+ ## Jellyfish 0.3.0 -- 2012-10-13
4
+
5
+ * Birthday!
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,236 @@
1
+ # Jellyfish
2
+
3
+ by Lin Jen-Shin ([godfat](http://godfat.org))
4
+
5
+ ## LINKS:
6
+
7
+ * [github](https://github.com/godfat/jellyfish)
8
+ * [rubygems](https://rubygems.org/gems/jellyfish)
9
+ * [rdoc](http://rdoc.info/github/godfat/jellyfish)
10
+
11
+ ## DESCRIPTION:
12
+
13
+ Pico web framework for building API-centric web applications, either
14
+ Rack applications or Rack middlewares. Under 200 lines of code.
15
+
16
+ ## DESIGN:
17
+
18
+ * Learn the HTTP way instead of using some pointless helpers
19
+ * Learn the Rack way instead of wrapping Rack functionality, again
20
+ * Learn regular expression for routes instead of custom syntax
21
+ * Embrace simplicity over convenience
22
+ * Don't make things complicated only for _some_ convenience, but
23
+ _great_ convenience, or simply stay simple for simplicity.
24
+
25
+ ## FEATURES:
26
+
27
+ * Minimal
28
+ * Simple
29
+ * No templates
30
+ * No ORM
31
+ * Regular expression routes, e.g. `get %r{/(\d+)}`
32
+ * String routes, e.g. `get '/'`
33
+ * Build for either Rack applications or Rack middlewares
34
+
35
+ ## WHY?
36
+
37
+ Because Sinatra is too complex and inconsistent for me.
38
+
39
+ ## REQUIREMENTS:
40
+
41
+ * Tested with MRI (official CRuby) 1.9.3, Rubinius and JRuby.
42
+
43
+ ## INSTALLATION:
44
+
45
+ gem install jellyfish
46
+
47
+ ## SYNOPSIS:
48
+
49
+ ### Hello Jellyfish, your lovely config.ru
50
+
51
+ ``` ruby
52
+ require 'jellyfish'
53
+ class Tank
54
+ include Jellyfish
55
+ get '/' do
56
+ "Jelly Kelly\n"
57
+ end
58
+ end
59
+ use Rack::ContentLength
60
+ run Tank.new
61
+ ```
62
+
63
+ ### Regular expression routes
64
+
65
+ ``` ruby
66
+ require 'jellyfish'
67
+ class Tank
68
+ include Jellyfish
69
+ get %r{^/(?<id>\d+)$} do |match|
70
+ "Jelly ##{match[:id]}\n"
71
+ end
72
+ end
73
+ use Rack::ContentLength
74
+ run Tank.new
75
+ ```
76
+
77
+ ### Different HTTP status
78
+
79
+ ``` ruby
80
+ require 'jellyfish'
81
+ class Tank
82
+ include Jellyfish
83
+ post '/' do
84
+ headers 'X-Jellyfish-Life' => '100'
85
+ headers_merge 'X-Jellyfish-Mana' => '200'
86
+ body "Jellyfish 100/200\n"
87
+ status 201
88
+ 'return is ignored in this case'
89
+ end
90
+ end
91
+ use Rack::ContentLength
92
+ run Tank.new
93
+ ```
94
+
95
+ ### Redirect helper
96
+
97
+ ``` ruby
98
+ require 'jellyfish'
99
+ class Tank
100
+ include Jellyfish
101
+ get '/lookup' do
102
+ found "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/"
103
+ end
104
+ end
105
+ use Rack::ContentLength
106
+ run Tank.new
107
+ ```
108
+
109
+ ### Crash-proof
110
+
111
+ ``` ruby
112
+ require 'jellyfish'
113
+ class Tank
114
+ include Jellyfish
115
+ get '/crash' do
116
+ raise 'crash'
117
+ end
118
+ end
119
+ use Rack::ContentLength
120
+ run Tank.new
121
+ ```
122
+
123
+ ### Custom error handler
124
+
125
+ ``` ruby
126
+ require 'jellyfish'
127
+ class Tank
128
+ include Jellyfish
129
+ handle NameError do |e|
130
+ status 403
131
+ "No one hears you: #{e.backtrace.first}\n"
132
+ end
133
+ get '/yell' do
134
+ yell
135
+ end
136
+ end
137
+ use Rack::ContentLength
138
+ run Tank.new
139
+ ```
140
+
141
+ ### Jellyfish as a middleware
142
+
143
+ ``` ruby
144
+ require 'jellyfish'
145
+ class Heater
146
+ include Jellyfish
147
+ get '/status' do
148
+ "30\u{2103}\n"
149
+ end
150
+ end
151
+
152
+ class Tank
153
+ include Jellyfish
154
+ get '/' do
155
+ "Jelly Kelly\n"
156
+ end
157
+ end
158
+
159
+ use Rack::ContentLength
160
+ use Heater
161
+ run Tank.new
162
+ ```
163
+
164
+ ### One huge tank
165
+
166
+ ``` ruby
167
+ require 'jellyfish'
168
+ class Heater
169
+ include Jellyfish
170
+ get '/status' do
171
+ "30\u{2103}\n"
172
+ end
173
+ end
174
+
175
+ class Tank
176
+ include Jellyfish
177
+ get '/' do
178
+ "Jelly Kelly\n"
179
+ end
180
+ end
181
+
182
+ HugeTank = Rack::Builder.new do
183
+ use Rack::ContentLength
184
+ use Heater
185
+ run Tank.new
186
+ end
187
+
188
+ run HugeTank
189
+ ```
190
+
191
+ ### Raise exceptions
192
+
193
+ ``` ruby
194
+ require 'jellyfish'
195
+ class Protector
196
+ include Jellyfish
197
+ handle Exception do |e|
198
+ "Protected: #{e}\n"
199
+ end
200
+ end
201
+
202
+ class Tank
203
+ include Jellyfish
204
+ handle_exceptions false # default is true, setting false here would make
205
+ # the outside Protector handle the exception
206
+ get '/' do
207
+ raise "Oops, tank broken"
208
+ end
209
+ end
210
+
211
+ use Rack::ContentLength
212
+ use Protector
213
+ run Tank.new
214
+ ```
215
+
216
+ ## CONTRIBUTORS:
217
+
218
+ * Lin Jen-Shin (@godfat)
219
+
220
+ ## LICENSE:
221
+
222
+ Apache License 2.0
223
+
224
+ Copyright (c) 2012, Lin Jen-Shin (godfat)
225
+
226
+ Licensed under the Apache License, Version 2.0 (the "License");
227
+ you may not use this file except in compliance with the License.
228
+ You may obtain a copy of the License at
229
+
230
+ <http://www.apache.org/licenses/LICENSE-2.0>
231
+
232
+ Unless required by applicable law or agreed to in writing, software
233
+ distributed under the License is distributed on an "AS IS" BASIS,
234
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
235
+ See the License for the specific language governing permissions and
236
+ limitations under the License.
data/Rakefile ADDED
@@ -0,0 +1,23 @@
1
+ # encoding: utf-8
2
+
3
+ begin
4
+ require "#{dir = File.dirname(__FILE__)}/task/gemgem"
5
+ rescue LoadError
6
+ sh "git submodule update --init"
7
+ exec Gem.ruby, "-S", "rake", *ARGV
8
+ end
9
+
10
+ Gemgem.dir = dir
11
+ ($LOAD_PATH << File.expand_path("#{Gemgem.dir}/lib")).uniq!
12
+
13
+ desc 'Generate gemspec'
14
+ task 'gem:spec' do
15
+ Gemgem.spec = Gemgem.create do |s|
16
+ require 'jellyfish/version'
17
+ s.name = 'jellyfish'
18
+ s.version = Jellyfish::VERSION
19
+ s.add_development_dependency('rack')
20
+ end
21
+
22
+ Gemgem.write
23
+ end
data/TODO.md ADDED
@@ -0,0 +1 @@
1
+ # TODO
data/config.ru ADDED
@@ -0,0 +1,60 @@
1
+
2
+ require 'jellyfish'
3
+
4
+ class Tank
5
+ include Jellyfish
6
+ handle_exceptions false
7
+
8
+ get '/' do
9
+ "Jelly Kelly\n"
10
+ end
11
+
12
+ get %r{^/(?<id>\d+)$} do |match|
13
+ "Jelly ##{match[:id]}\n"
14
+ end
15
+
16
+ post '/' do
17
+ headers 'X-Jellyfish-Life' => '100'
18
+ headers_merge 'X-Jellyfish-Mana' => '200'
19
+ body "Jellyfish 100/200\n"
20
+ status 201
21
+
22
+ 'return is ignored in this case'
23
+ end
24
+
25
+ get '/env' do
26
+ "#{env.inspect}\n"
27
+ end
28
+
29
+ get '/lookup' do
30
+ found "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/"
31
+ end
32
+
33
+ get '/crash' do
34
+ raise 'crash'
35
+ end
36
+
37
+ handle NameError do |e|
38
+ status 403
39
+ "No one hears you: #{e.backtrace.first}\n"
40
+ end
41
+
42
+ get '/yell' do
43
+ yell
44
+ end
45
+ end
46
+
47
+ class Heater
48
+ include Jellyfish
49
+ get '/status' do
50
+ "30\u{2103}\n"
51
+ end
52
+ end
53
+
54
+ HugeTank = Rack::Builder.new do
55
+ use Rack::ContentLength
56
+ use Heater
57
+ run Tank.new
58
+ end
59
+
60
+ run HugeTank
data/jellyfish.gemspec ADDED
@@ -0,0 +1,45 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ Gem::Specification.new do |s|
4
+ s.name = "jellyfish"
5
+ s.version = "0.3.0"
6
+
7
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
8
+ s.authors = ["Lin Jen-Shin (godfat)"]
9
+ s.date = "2012-10-13"
10
+ s.description = "Pico web framework for building API-centric web applications, either\nRack applications or Rack middlewares. Under 200 lines of code."
11
+ s.email = ["godfat (XD) godfat.org"]
12
+ s.files = [
13
+ ".gitmodules",
14
+ ".travis.yml",
15
+ "CHANGES.md",
16
+ "LICENSE",
17
+ "README.md",
18
+ "Rakefile",
19
+ "TODO.md",
20
+ "config.ru",
21
+ "jellyfish.gemspec",
22
+ "lib/jellyfish.rb",
23
+ "lib/jellyfish/public/302.html",
24
+ "lib/jellyfish/public/404.html",
25
+ "lib/jellyfish/public/500.html",
26
+ "lib/jellyfish/version.rb",
27
+ "task/.gitignore",
28
+ "task/gemgem.rb"]
29
+ s.homepage = "https://github.com/godfat/jellyfish"
30
+ s.require_paths = ["lib"]
31
+ s.rubygems_version = "1.8.24"
32
+ s.summary = "Pico web framework for building API-centric web applications, either"
33
+
34
+ if s.respond_to? :specification_version then
35
+ s.specification_version = 3
36
+
37
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
38
+ s.add_development_dependency(%q<rack>, [">= 0"])
39
+ else
40
+ s.add_dependency(%q<rack>, [">= 0"])
41
+ end
42
+ else
43
+ s.add_dependency(%q<rack>, [">= 0"])
44
+ end
45
+ end
data/lib/jellyfish.rb ADDED
@@ -0,0 +1,190 @@
1
+
2
+ module Jellyfish
3
+ autoload :VERSION, 'jellyfish/version'
4
+
5
+ REQUEST_METHOD = 'REQUEST_METHOD'
6
+ PATH_INFO = 'PATH_INFO'
7
+ LOCATION = 'Location'
8
+ RACK_ERRORS = 'rack.errors'
9
+
10
+ # -----------------------------------------------------------------
11
+
12
+ class Respond < RuntimeError
13
+ def headers
14
+ @headers ||= {'Content-Type' => 'text/html'}
15
+ end
16
+
17
+ def body
18
+ @body ||= [File.read("#{Jellyfish.public_root}/#{status}.html")]
19
+ end
20
+ end
21
+
22
+ class NotFound < Respond; def status; 404; end; end
23
+ class InternalError < Respond; def status; 500; end; end
24
+ class Found < Respond
25
+ attr_reader :url
26
+ def initialize url; @url = url ; end
27
+ def status ; 302 ; end
28
+ def headers ; super.merge(LOCATION => url) ; end
29
+ def body ; super.map{ |b| b.gsub('VAR_URL', url) }; end
30
+ end
31
+
32
+ # -----------------------------------------------------------------
33
+
34
+ class Controller
35
+ include Jellyfish
36
+ attr_reader :routes, :env
37
+ def initialize routes
38
+ @routes = routes
39
+ end
40
+
41
+ def call env
42
+ @env = env
43
+ block_call(*dispatch)
44
+ end
45
+
46
+ def block_call argument, block
47
+ ret = instance_exec(argument, &block)
48
+ body ret if body.nil? # prefer explicitly set values
49
+ [status || 200, headers || {}, body]
50
+ end
51
+
52
+ def forward ; raise(NotFound.new) ; end
53
+ def found url; raise(Found.new(url)); end
54
+ alias_method :redirect, :found
55
+
56
+ def path_info ; env[PATH_INFO] || '/' ; end
57
+ def request_method; env[REQUEST_METHOD] || 'GET'; end
58
+
59
+ %w[status headers].each do |field|
60
+ module_eval <<-RUBY
61
+ def #{field} value=nil
62
+ if value.nil?
63
+ @#{field}
64
+ else
65
+ @#{field} = value
66
+ end
67
+ end
68
+ RUBY
69
+ end
70
+
71
+ def body value=nil
72
+ if value.nil?
73
+ @body
74
+ elsif value.respond_to?(:each) # per rack SPEC
75
+ @body = value
76
+ else
77
+ @body = [value]
78
+ end
79
+ end
80
+
81
+ def headers_merge value
82
+ if headers.nil?
83
+ headers(value)
84
+ else
85
+ headers(headers.merge(value))
86
+ end
87
+ end
88
+
89
+ private
90
+ def actions
91
+ routes[request_method.downcase] || raise(NotFound.new)
92
+ end
93
+
94
+ def dispatch
95
+ actions.find{ |(route, block)|
96
+ case route
97
+ when Regexp
98
+ match = route.match(path_info)
99
+ break match, block if match
100
+ when String
101
+ break route, block if route == path_info
102
+ end
103
+ } || raise(NotFound.new)
104
+ end
105
+ end
106
+
107
+ # -----------------------------------------------------------------
108
+
109
+ module DSL
110
+ def handlers; @handlers ||= {}; end
111
+ def routes ; @routes ||= {}; end
112
+
113
+ def handle_exceptions value=nil
114
+ if value.nil?
115
+ @handle_exceptions
116
+ else
117
+ @handle_exceptions = value
118
+ end
119
+ end
120
+
121
+ def handle exception, &block; handlers[exception] = block; end
122
+
123
+ %w[options get head post put delete patch].each do |method|
124
+ module_eval <<-RUBY
125
+ def #{method} route, &block
126
+ (routes['#{method}'] ||= []) << [route, block]
127
+ end
128
+ RUBY
129
+ end
130
+ end
131
+
132
+ # -----------------------------------------------------------------
133
+
134
+ def initialize app=nil; @app = app; end
135
+
136
+ def call env
137
+ controller = Controller.new(self.class.routes)
138
+ controller.call(env)
139
+ rescue NotFound => e # forward
140
+ if app
141
+ protect(controller, env){ app.call(env) }
142
+ else
143
+ handle(controller, e)
144
+ end
145
+ rescue Exception => e
146
+ handle(controller, e, env[RACK_ERRORS])
147
+ end
148
+
149
+ def protect controller, env
150
+ yield
151
+ rescue Exception => e
152
+ handle(controller, e, env[RACK_ERRORS])
153
+ end
154
+
155
+ private
156
+ def handle controller, e, stderr=nil
157
+ raise e unless self.class.handle_exceptions
158
+ handler = self.class.handlers.find{ |klass, block|
159
+ break block if e.kind_of?(klass)
160
+ }
161
+ if handler
162
+ controller.block_call(e, handler)
163
+ elsif e.kind_of?(Respond) # InternalError ends up here if no handlers
164
+ [e.status, e.headers, e.body]
165
+ else # fallback and see if there's any InternalError handler
166
+ log_error(e, stderr)
167
+ handle(controller, InternalError.new)
168
+ end
169
+ end
170
+
171
+ def log_error e, stderr
172
+ return unless stderr
173
+ stderr.puts("[#{self.class.name}] #{e.inspect} #{e.backtrace}")
174
+ end
175
+
176
+ # -----------------------------------------------------------------
177
+
178
+ def self.included mod
179
+ mod.__send__(:extend, DSL)
180
+ mod.__send__(:attr_reader, :app)
181
+ mod.handle_exceptions(true)
182
+ end
183
+
184
+ # -----------------------------------------------------------------
185
+
186
+ module_function
187
+ def public_root
188
+ "#{File.dirname(__FILE__)}/jellyfish/public"
189
+ end
190
+ end
@@ -0,0 +1,10 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
5
+ <meta http-equiv="refresh" content="0;URL='VAR_URL'">
6
+ </head>
7
+ <body>
8
+ <h1>Jellyfish found: VAR_URL</h1>
9
+ </body>
10
+ </html>
@@ -0,0 +1,9 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
5
+ </head>
6
+ <body>
7
+ <h1>Jellyfish not found</h1>
8
+ </body>
9
+ </html>
@@ -0,0 +1,9 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
5
+ </head>
6
+ <body>
7
+ <h1>Jellyfish crashed</h1>
8
+ </body>
9
+ </html>
@@ -0,0 +1,4 @@
1
+
2
+ module Jellyfish
3
+ VERSION = '0.3.0'
4
+ end
data/task/.gitignore ADDED
@@ -0,0 +1 @@
1
+ *.rbc
data/task/gemgem.rb ADDED
@@ -0,0 +1,267 @@
1
+
2
+ require 'pathname'
3
+
4
+ module Gemgem
5
+ class << self
6
+ attr_accessor :dir, :spec
7
+ end
8
+
9
+ module_function
10
+ def create
11
+ yield(spec = Gem::Specification.new{ |s|
12
+ s.authors = ['Lin Jen-Shin (godfat)']
13
+ s.email = ['godfat (XD) godfat.org']
14
+
15
+ s.description = description.join
16
+ s.summary = description.first
17
+
18
+ s.rubygems_version = Gem::VERSION
19
+ s.date = Time.now.strftime('%Y-%m-%d')
20
+ s.files = gem_files
21
+ s.test_files = gem_files.grep(%r{^test/(.+?/)*test_.+?\.rb$})
22
+ s.executables = Dir['bin/*'].map{ |f| File.basename(f) }
23
+ s.require_paths = %w[lib]
24
+ })
25
+ spec.homepage ||= "https://github.com/godfat/#{spec.name}"
26
+ spec
27
+ end
28
+
29
+ def readme
30
+ path = %w[README.md README].find{ |name|
31
+ File.exist?("#{Gemgem.dir}/#{name}")
32
+ }
33
+ @readme ||=
34
+ if path
35
+ ps = "##{File.read(path)}".
36
+ scan(/((#+)[^\n]+\n\n.+?(?=\n\n\2[^#\n]+\n))/m).map(&:first)
37
+ ps.inject({'HEADER' => ps.first}){ |r, s, i|
38
+ r[s[/\w+/]] = s
39
+ r
40
+ }
41
+ else
42
+ {}
43
+ end
44
+ end
45
+
46
+ def description
47
+ @description ||= (readme['DESCRIPTION']||'').sub(/.+\n\n/, '').lines.to_a
48
+ end
49
+
50
+ def changes
51
+ path = %w[CHANGES.md CHANGES].find{ |name|
52
+ File.exist?("#{Gemgem.dir}/#{name}")
53
+ }
54
+ @changes ||=
55
+ if path
56
+ date = '\d+{4}\-\d+{2}\-\d{2}'
57
+ File.read(path).match(
58
+ /([^\n]+#{date}\n\n(.+?))(?=\n\n[^\n]+#{date}\n|\Z)/m)[1]
59
+ else
60
+ ''
61
+ end
62
+ end
63
+
64
+ def ann_md
65
+ "#{readme['HEADER'].sub(/([\w\-]+)/, "[\\1](#{spec.homepage})")}\n\n" \
66
+ "##{readme['DESCRIPTION'][/[^\n]+\n\n[^\n]+/]}\n\n" \
67
+ "### CHANGES:\n\n" \
68
+ "###{changes}\n\n" \
69
+ "##{readme['INSTALLATION']}\n\n" +
70
+ if readme['SYNOPSIS'] then "##{readme['SYNOPSIS'][/[^\n]+\n\n[^\n]+/]}"
71
+ else '' end
72
+ end
73
+
74
+ def ann_html
75
+ gem 'nokogiri'
76
+ gem 'kramdown'
77
+
78
+ IO.popen('kramdown', 'r+') do |md|
79
+ md.puts Gemgem.ann_md
80
+ md.close_write
81
+ require 'nokogiri'
82
+ html = Nokogiri::XML.parse("<gemgem>#{md.read}</gemgem>")
83
+ html.css('*').each{ |n| n.delete('id') }
84
+ html.root.children.to_html
85
+ end
86
+ end
87
+
88
+ def ann_email
89
+ "#{readme['HEADER'].sub(/([\w\-]+)/, "\\1 <#{spec.homepage}>")}\n\n" \
90
+ "#{readme['DESCRIPTION']}\n\n" \
91
+ "#{readme['INSTALLATION']}\n\n" +
92
+ if readme['SYNOPSIS'] then "##{readme['SYNOPSIS']}\n\n" else '' end +
93
+ "## CHANGES:\n\n" \
94
+ "##{changes}\n\n"
95
+ end
96
+
97
+ def gem_tag
98
+ "#{spec.name}-#{spec.version}"
99
+ end
100
+
101
+ def write
102
+ File.open("#{dir}/#{spec.name}.gemspec", 'w'){ |f|
103
+ f << split_lines(spec.to_ruby) }
104
+ end
105
+
106
+ def split_lines ruby
107
+ ruby.gsub(/(.+?)\[(.+?)\]/){ |s|
108
+ if $2.index(',')
109
+ "#{$1}[\n #{$2.split(',').map(&:strip).join(",\n ")}]"
110
+ else
111
+ s
112
+ end
113
+ }
114
+ end
115
+
116
+ def all_files
117
+ @all_files ||= find_files(Pathname.new(dir)).map{ |file|
118
+ if file.to_s =~ %r{\.git/|\.git$}
119
+ nil
120
+ else
121
+ file.to_s
122
+ end
123
+ }.compact.sort
124
+ end
125
+
126
+ def gem_files
127
+ @gem_files ||= all_files - ignored_files
128
+ end
129
+
130
+ def ignored_files
131
+ @ignored_file ||= all_files.select{ |path| ignore_patterns.find{ |ignore|
132
+ path =~ ignore && !git_files.include?(path)}}
133
+ end
134
+
135
+ def git_files
136
+ @git_files ||= if File.exist?("#{dir}/.git")
137
+ `git ls-files`.split("\n")
138
+ else
139
+ []
140
+ end
141
+ end
142
+
143
+ # protected
144
+ def find_files path
145
+ path.children.select(&:file?).map{|file| file.to_s[(dir.size+1)..-1]} +
146
+ path.children.select(&:directory?).map{|dir| find_files(dir)}.flatten
147
+ end
148
+
149
+ def ignore_patterns
150
+ @ignore_files ||= expand_patterns(
151
+ gitignore.split("\n").reject{ |pattern|
152
+ pattern.strip == ''
153
+ }).map{ |pattern| %r{^([^/]+/)*?#{Regexp.escape(pattern)}(/[^/]+)*?$} }
154
+ end
155
+
156
+ def expand_patterns pathes
157
+ pathes.map{ |path|
158
+ if path !~ /\*/
159
+ path
160
+ else
161
+ expand_patterns(
162
+ Dir[path] +
163
+ Pathname.new(File.dirname(path)).children.select(&:directory?).
164
+ map{ |prefix| "#{prefix}/#{File.basename(path)}" })
165
+ end
166
+ }.flatten
167
+ end
168
+
169
+ def gitignore
170
+ if File.exist?(path = "#{dir}/.gitignore")
171
+ File.read(path)
172
+ else
173
+ ''
174
+ end
175
+ end
176
+ end
177
+
178
+ namespace :gem do
179
+
180
+ desc 'Install gem'
181
+ task :install => [:build] do
182
+ sh("#{Gem.ruby} -S gem install pkg/#{Gemgem.gem_tag}")
183
+ end
184
+
185
+ desc 'Build gem'
186
+ task :build => [:spec] do
187
+ sh("#{Gem.ruby} -S gem build #{Gemgem.spec.name}.gemspec")
188
+ sh("mkdir -p pkg")
189
+ sh("mv #{Gemgem.gem_tag}.gem pkg/")
190
+ end
191
+
192
+ desc 'Release gem'
193
+ task :release => [:spec, :check, :build] do
194
+ sh("git tag #{Gemgem.gem_tag}")
195
+ sh("git push")
196
+ sh("git push --tags")
197
+ sh("#{Gem.ruby} -S gem push pkg/#{Gemgem.gem_tag}.gem")
198
+ end
199
+
200
+ task :check do
201
+ ver = Gemgem.spec.version.to_s
202
+
203
+ if ENV['VERSION'].nil?
204
+ puts("\e[35mExpected " \
205
+ "\e[33mVERSION\e[35m=\e[33m#{ver}\e[0m")
206
+ exit(1)
207
+
208
+ elsif ENV['VERSION'] != ver
209
+ puts("\e[35mExpected \e[33mVERSION\e[35m=\e[33m#{ver} " \
210
+ "\e[35mbut got\n " \
211
+ "\e[33mVERSION\e[35m=\e[33m#{ENV['VERSION']}\e[0m")
212
+ exit(2)
213
+ end
214
+ end
215
+
216
+ end # of gem namespace
217
+
218
+ desc 'Run tests in memory'
219
+ task :test do
220
+ require 'bacon'
221
+ Bacon.extend(Bacon::TestUnitOutput)
222
+ Bacon.summary_on_exit
223
+ $LOAD_PATH.unshift('lib')
224
+ Dir['./test/**/test_*.rb'].each{ |file| require file[0..-4] }
225
+ end
226
+
227
+ desc 'Run tests with shell'
228
+ task 'test:shell', :RUBY_OPTS do |t, args|
229
+ files = Dir['test/**/test_*.rb'].join(' ')
230
+
231
+ cmd = [Gem.ruby, args[:RUBY_OPTS],
232
+ '-I', 'lib', '-S', 'bacon', '--quiet', files]
233
+
234
+ sh(cmd.compact.join(' '))
235
+ end
236
+
237
+ desc 'Generate ann markdown'
238
+ task 'ann:md' => ['gem:spec'] do
239
+ puts Gemgem.ann_md
240
+ end
241
+
242
+ desc 'Generate ann html'
243
+ task 'ann:html' => ['gem:spec'] do
244
+ puts Gemgem.ann_html
245
+ end
246
+
247
+ desc 'Generate ann email'
248
+ task 'ann:email' => ['gem:spec'] do
249
+ puts Gemgem.ann_email
250
+ end
251
+
252
+ desc 'Generate rdoc'
253
+ task :doc => ['gem:spec'] do
254
+ sh("yardoc -o rdoc --main README.md" \
255
+ " --files #{Gemgem.spec.extra_rdoc_files.join(',')}")
256
+ end
257
+
258
+ desc 'Remove ignored files'
259
+ task :clean => ['gem:spec'] do
260
+ trash = "~/.Trash/#{Gemgem.spec.name}/"
261
+ sh "mkdir -p #{trash}" unless File.exist?(File.expand_path(trash))
262
+ Gemgem.ignored_files.each{ |file| sh "mv #{file} #{trash}" }
263
+ end
264
+
265
+ task :default do
266
+ puts `#{Gem.ruby} -S #{$PROGRAM_NAME} -T`
267
+ end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: jellyfish
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Lin Jen-Shin (godfat)
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-10-13 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rack
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ! '>='
28
+ - !ruby/object:Gem::Version
29
+ version: '0'
30
+ description: ! 'Pico web framework for building API-centric web applications, either
31
+
32
+ Rack applications or Rack middlewares. Under 200 lines of code.'
33
+ email:
34
+ - godfat (XD) godfat.org
35
+ executables: []
36
+ extensions: []
37
+ extra_rdoc_files: []
38
+ files:
39
+ - .gitmodules
40
+ - .travis.yml
41
+ - CHANGES.md
42
+ - LICENSE
43
+ - README.md
44
+ - Rakefile
45
+ - TODO.md
46
+ - config.ru
47
+ - jellyfish.gemspec
48
+ - lib/jellyfish.rb
49
+ - lib/jellyfish/public/302.html
50
+ - lib/jellyfish/public/404.html
51
+ - lib/jellyfish/public/500.html
52
+ - lib/jellyfish/version.rb
53
+ - task/.gitignore
54
+ - task/gemgem.rb
55
+ homepage: https://github.com/godfat/jellyfish
56
+ licenses: []
57
+ post_install_message:
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ none: false
63
+ requirements:
64
+ - - ! '>='
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ none: false
69
+ requirements:
70
+ - - ! '>='
71
+ - !ruby/object:Gem::Version
72
+ version: '0'
73
+ requirements: []
74
+ rubyforge_project:
75
+ rubygems_version: 1.8.24
76
+ signing_key:
77
+ specification_version: 3
78
+ summary: Pico web framework for building API-centric web applications, either
79
+ test_files: []
80
+ has_rdoc: