prezjordan-toto 0.4.9

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/.gitignore ADDED
@@ -0,0 +1,5 @@
1
+ *.sw?
2
+ .DS_Store
3
+ coverage
4
+ rdoc
5
+ pkg
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 cloudhead
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.
data/README.md ADDED
@@ -0,0 +1,162 @@
1
+ toto
2
+ ====
3
+
4
+ the tiniest blogging engine in Oz!
5
+
6
+ introduction
7
+ ------------
8
+
9
+ toto is a git-powered, minimalist blog engine for the hackers of Oz. The engine weighs around ~300 sloc at its worse.
10
+ There is no toto client, at least for now; everything goes through git.
11
+
12
+ blog in 10 seconds
13
+ ------------------
14
+
15
+ $ git clone git://github.com/cloudhead/dorothy.git myblog
16
+ $ cd myblog
17
+ $ heroku create myblog
18
+ $ git push heroku master
19
+
20
+ philosophy
21
+ ----------
22
+
23
+ Everything that can be done better with another tool should be, but one should not have too much pie to stay fit.
24
+ In other words, toto does away with web frameworks or DSLs such as sinatra, and is built right on top of **rack**.
25
+ There is no database or ORM either, we use plain text files.
26
+
27
+ Toto was designed to be used with a reverse-proxy cache, such as [Varnish](http://varnish-cache.org).
28
+ This makes it an ideal candidate for [heroku](http://heroku.com).
29
+
30
+ Oh, and everything that can be done with git, _is_.
31
+
32
+ how it works
33
+ ------------
34
+
35
+ - content is entirely managed through **git**; you get full fledged version control for free.
36
+ - articles are stored as _.txt_ files, with embeded metadata (in yaml format).
37
+ - articles are processed through a markdown converter (rdiscount) by default.
38
+ - templating is done through **ERB**.
39
+ - toto is built right on top of **Rack**.
40
+ - toto was built to take advantage of _HTTP caching_.
41
+ - toto was built with heroku in mind.
42
+ - comments are handled by [disqus](http://disqus.com)
43
+ - individual articles can be accessed through urls such as _/2009/11/21/blogging-with-toto_
44
+ - the archives can be accessed by year, month or day, wih the same format as above.
45
+ - arbitrary metadata can be included in articles files, and accessed from the templates.
46
+ - summaries are generated intelligently by toto, following the `:max` setting you give it.
47
+ - you can also define how long your summary is, by adding `~` at the end of it (`:delim`).
48
+
49
+ dorothy
50
+ -------
51
+
52
+ Dorothy is toto's default template, you can get it at <http://github.com/cloudhead/dorothy>. It
53
+ comes with a very minimalistic but functional template, and a _config.ru_ file to get you started.
54
+ It also includes a _.gems_ file, for heroku.
55
+
56
+ synopsis
57
+ --------
58
+
59
+ One would start by installing _toto_, with `sudo gem install toto`, and then forking or
60
+ cloning the `dorothy` repo, to get a basic skeleton:
61
+
62
+ $ git clone git://github.com/cloudhead/dorothy.git weblog
63
+ $ cd weblog/
64
+
65
+ One would then edit the template at will, it has the following structure:
66
+
67
+ templates/
68
+ |
69
+ +- layout.rhtml # the main site layout, shared by all pages
70
+ |
71
+ +- index.builder # the builder template for the atom feed
72
+ |
73
+ +- pages/ # pages, such as home, about, etc go here
74
+ |
75
+ +- index.rhtml # the default page loaded from `/`, it displays the list of articles
76
+ |
77
+ +- article.rhtml # the article (post) partial and page
78
+ |
79
+ +- about.rhtml
80
+
81
+ One could then create a .txt article file in the `articles/` folder, and make sure it has the following format:
82
+
83
+ title: The Wonderful Wizard of Oz
84
+ author: Lyman Frank Baum
85
+ date: 1900/05/17
86
+
87
+ Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry,
88
+ who was a farmer, and Aunt Em, who was the farmer's wife.
89
+
90
+ If one is familiar with webby or aerial, this shouldn't look funny. Basically the top of the file is in YAML format,
91
+ and the rest of it is the blog post. They are delimited by an empty line `/\n\n/`, as you can see above.
92
+ None of the information is compulsory, but it's strongly encouraged you specify it.
93
+ Note that one can also use `rake` to create an article stub, with `rake new`.
94
+
95
+ Once he finishes writing his beautiful tale, one can push to the git repo, as usual:
96
+
97
+ $ git add articles/wizard-of-oz.txt
98
+ $ git commit -m 'wrote the wizard of oz.'
99
+ $ git push remote master
100
+
101
+ Where `remote` is the name of your remote git repository. The article is now published.
102
+
103
+ ### deployment
104
+
105
+ Toto is built on top of **Rack**, and hence has a **rackup** file: _config.ru_.
106
+
107
+ #### on your own server
108
+
109
+ Once you have created the remote git repo, and pushed your changes to it, you can run toto with any Rack compliant web server,
110
+ such as **thin**, **mongrel** or **unicorn**.
111
+
112
+ With thin, you would do something like:
113
+
114
+ $ thin start -R config.ru
115
+
116
+ With unicorn, you can just do:
117
+
118
+ $ unicorn
119
+
120
+ #### on heroku
121
+
122
+ Toto was designed to work well with [heroku](http://heroku.com), it makes the most out of it's state-of-the-art caching,
123
+ by setting the _Cache-Control_ and _Etag_ HTTP headers. Deploying on Heroku is really easy, just get the heroku gem,
124
+ create a heroku app with `heroku create`, and push with `git push heroku master`.
125
+
126
+ $ heroku create weblog
127
+ $ git push heroku master
128
+ $ heroku open
129
+
130
+ ### configuration
131
+
132
+ You can configure toto, by modifying the _config.ru_ file. For example, if you want to set the blog author to 'John Galt',
133
+ you could add `set :author, 'John Galt'` inside the `Toto::Server.new` block. Here are the defaults, to get you started:
134
+
135
+ set :author, ENV['USER'] # blog author
136
+ set :title, Dir.pwd.split('/').last # site title
137
+ set :url, 'http://example.com' # site root URL
138
+ set :prefix, '' # common path prefix for all pages
139
+ set :root, "index" # page to load on /
140
+ set :date, lambda {|now| now.strftime("%d/%m/%Y") } # date format for articles
141
+ set :markdown, :smart # use markdown + smart-mode
142
+ set :disqus, false # disqus id, or false
143
+ set :summary, :max => 150, :delim => /~\n/ # length of article summary and delimiter
144
+ set :ext, 'txt' # file extension for articles
145
+ set :cache, 28800 # cache site for 8 hours
146
+
147
+ set :to_html do |path, page, ctx| # returns an html, from a path & context
148
+ ERB.new(File.read("#{path}/#{page}.rhtml")).result(ctx)
149
+ end
150
+
151
+ set :error do |code| # The HTML for your error page
152
+ "<font style='font-size:300%'>toto, we're not in Kansas anymore (#{code})</font>"
153
+ end
154
+
155
+ thanks
156
+ ------
157
+
158
+ To heroku for making this easy as pie.
159
+ To adam wiggins, as I stole a couple of ideas from Scanty.
160
+ To the developpers of Rack, for making such an awesome platform.
161
+
162
+ Copyright (c) 2009-2010 cloudhead. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,35 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "prezjordan-toto"
8
+ gem.summary = %Q{prezjordan's fork of the tiniest blog-engine in Oz}
9
+ gem.description = %Q{prezjordan's fork of the tiniest blog-engine in Oz}
10
+ gem.email = "scalesjordan@gmail.com"
11
+ gem.homepage = "http://github.com/prezjordan/toto"
12
+ gem.authors = ["prezjordan"]
13
+ gem.add_development_dependency "riot"
14
+ gem.add_dependency "builder"
15
+ gem.add_dependency "rack"
16
+ if RUBY_PLATFORM =~ /win32/
17
+ gem.add_dependency "maruku"
18
+ else
19
+ gem.add_dependency "rdiscount"
20
+ end
21
+ end
22
+ Jeweler::GemcutterTasks.new
23
+ rescue LoadError
24
+ puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
25
+ end
26
+
27
+ require 'rake/testtask'
28
+ Rake::TestTask.new(:test) do |test|
29
+ test.libs << 'lib' << 'test'
30
+ test.pattern = 'test/**/*_test.rb'
31
+ test.verbose = true
32
+ end
33
+
34
+ task :test => :check_dependencies
35
+ task :default => :test
data/TODO ADDED
@@ -0,0 +1,2 @@
1
+ TODO
2
+ ====
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.4.9
data/lib/ext/ext.rb ADDED
@@ -0,0 +1,52 @@
1
+ class Object
2
+ def meta_def name, &blk
3
+ (class << self; self; end).instance_eval do
4
+ define_method(name, &blk)
5
+ end
6
+ end
7
+ end
8
+
9
+ class String
10
+ def slugize
11
+ self.downcase.gsub(/&/, 'and').gsub(/\s+/, '-').gsub(/[^a-z0-9-]/, '')
12
+ end
13
+
14
+ def humanize
15
+ self.capitalize.gsub(/[-_]+/, ' ')
16
+ end
17
+
18
+ if RUBY_VERSION < "1.9"
19
+ def bytesize
20
+ size
21
+ end
22
+ end
23
+ end
24
+
25
+ class Fixnum
26
+ def ordinal
27
+ # 1 => 1st
28
+ # 2 => 2nd
29
+ # 3 => 3rd
30
+ # ...
31
+ case self % 100
32
+ when 11..13; "#{self}th"
33
+ else
34
+ case self % 10
35
+ when 1; "#{self}st"
36
+ when 2; "#{self}nd"
37
+ when 3; "#{self}rd"
38
+ else "#{self}th"
39
+ end
40
+ end
41
+ end
42
+ end
43
+
44
+ class Date
45
+ # This check is for people running Toto with ActiveSupport, avoid a collision
46
+ unless respond_to? :iso8601
47
+ # Return the date as a String formatted according to ISO 8601.
48
+ def iso8601
49
+ ::Time.utc(year, month, day, 0, 0, 0, 0).iso8601
50
+ end
51
+ end
52
+ end
data/lib/toto.rb ADDED
@@ -0,0 +1,359 @@
1
+ require 'yaml'
2
+ require 'date'
3
+ require 'erb'
4
+ require 'rack'
5
+ require 'digest'
6
+ require 'open-uri'
7
+
8
+ if RUBY_PLATFORM =~ /win32/
9
+ require 'maruku'
10
+ Markdown = Maruku
11
+ else
12
+ require 'rdiscount'
13
+ end
14
+
15
+ require 'builder'
16
+
17
+ $:.unshift File.dirname(__FILE__)
18
+
19
+ require 'ext/ext'
20
+
21
+ module Toto
22
+ Paths = {
23
+ :templates => "templates",
24
+ :pages => "templates/pages",
25
+ :articles => "articles"
26
+ }
27
+
28
+ def self.env
29
+ ENV['RACK_ENV'] || 'production'
30
+ end
31
+
32
+ def self.env= env
33
+ ENV['RACK_ENV'] = env
34
+ end
35
+
36
+ module Template
37
+ def to_html page, config, &blk
38
+ path = ([:layout, :repo].include?(page) ? Paths[:templates] : Paths[:pages])
39
+ config[:to_html].call(path, page, binding)
40
+ end
41
+
42
+ def markdown text
43
+ if (options = @config[:markdown])
44
+ Markdown.new(text.to_s.strip, *(options.eql?(true) ? [] : options)).to_html
45
+ else
46
+ text.strip
47
+ end
48
+ end
49
+
50
+ def method_missing m, *args, &blk
51
+ self.keys.include?(m) ? self[m] : super
52
+ end
53
+
54
+ def self.included obj
55
+ obj.class_eval do
56
+ define_method(obj.to_s.split('::').last.downcase) { self }
57
+ end
58
+ end
59
+ end
60
+
61
+ class Site
62
+ def initialize config
63
+ @config = config
64
+ end
65
+
66
+ def [] *args
67
+ @config[*args]
68
+ end
69
+
70
+ def []= key, value
71
+ @config.set key, value
72
+ end
73
+
74
+ def index type = :html
75
+ articles = type == :html ? self.articles.reverse : self.articles
76
+ {:articles => articles.map do |article|
77
+ Article.new article, @config
78
+ end}.merge archives
79
+ end
80
+
81
+ def archives filter = ""
82
+ entries = ! self.articles.empty??
83
+ self.articles.select do |a|
84
+ filter !~ /^\d{4}/ || File.basename(a) =~ /^#{filter}/
85
+ end.reverse.map do |article|
86
+ Article.new article, @config
87
+ end : []
88
+
89
+ return :archives => Archives.new(entries, @config)
90
+ end
91
+
92
+ def article route
93
+ Article.new("#{Paths[:articles]}/#{route.join('-')}.#{self[:ext]}", @config).load
94
+ end
95
+
96
+ def /
97
+ self[:root]
98
+ end
99
+
100
+ def go route, env = {}, type = :html
101
+ route << self./ if route.empty?
102
+ type, path = type =~ /html|xml|json/ ? type.to_sym : :html, route.join('/')
103
+ context = lambda do |data, page|
104
+ Context.new(data, @config, path, env).render(page, type)
105
+ end
106
+
107
+ body, status = if Context.new.respond_to?(:"to_#{type}")
108
+ if route.first =~ /\d{4}/
109
+ case route.size
110
+ when 1..3
111
+ context[archives(route * '-'), :archives]
112
+ when 4
113
+ context[article(route), :article]
114
+ else http 400
115
+ end
116
+ elsif respond_to?(path)
117
+ context[send(path, type), path.to_sym]
118
+ elsif (repo = @config[:github][:repos].grep(/#{path}/).first) &&
119
+ !@config[:github][:user].empty?
120
+ context[Repo.new(repo, @config), :repo]
121
+ else
122
+ context[{}, path.to_sym]
123
+ end
124
+ else
125
+ http 400
126
+ end
127
+
128
+ rescue Errno::ENOENT => e
129
+ return :body => http(404).first, :type => :html, :status => 404
130
+ else
131
+ return :body => body || "", :type => type, :status => status || 200
132
+ end
133
+
134
+ protected
135
+
136
+ def http code
137
+ [@config[:error].call(code), code]
138
+ end
139
+
140
+ def articles
141
+ self.class.articles self[:ext]
142
+ end
143
+
144
+ def self.articles ext
145
+ Dir["#{Paths[:articles]}/*.#{ext}"].sort_by {|entry| File.basename(entry) }
146
+ end
147
+
148
+ class Context
149
+ include Template
150
+ attr_reader :env
151
+
152
+ def initialize ctx = {}, config = {}, path = "/", env = {}
153
+ @config, @context, @path, @env = config, ctx, path, env
154
+ @articles = Site.articles(@config[:ext]).reverse.map do |a|
155
+ Article.new(a, @config)
156
+ end
157
+
158
+ ctx.each do |k, v|
159
+ meta_def(k) { ctx.instance_of?(Hash) ? v : ctx.send(k) }
160
+ end
161
+ end
162
+
163
+ def title
164
+ @config[:title]
165
+ end
166
+
167
+ def render page, type
168
+ content = to_html page, @config
169
+ type == :html ? to_html(:layout, @config, &Proc.new { content }) : send(:"to_#{type}", page)
170
+ end
171
+
172
+ def to_xml page
173
+ xml = Builder::XmlMarkup.new(:indent => 2)
174
+ instance_eval File.read("#{Paths[:templates]}/#{page}.builder")
175
+ end
176
+ alias :to_atom to_xml
177
+
178
+ def method_missing m, *args, &blk
179
+ @context.respond_to?(m) ? @context.send(m, *args, &blk) : super
180
+ end
181
+ end
182
+ end
183
+
184
+ class Repo < Hash
185
+ include Template
186
+
187
+ README = "https://github.com/%s/%s/raw/master/README.%s"
188
+
189
+ def initialize name, config
190
+ self[:name], @config = name, config
191
+ end
192
+
193
+ def readme
194
+ markdown open(README %
195
+ [@config[:github][:user], self[:name], @config[:github][:ext]]).read
196
+ rescue Timeout::Error, OpenURI::HTTPError => e
197
+ "This page isn't available."
198
+ end
199
+ alias :content readme
200
+ end
201
+
202
+ class Archives < Array
203
+ include Template
204
+
205
+ def initialize articles, config
206
+ self.replace articles
207
+ @config = config
208
+ end
209
+
210
+ def [] a
211
+ a.is_a?(Range) ? self.class.new(self.slice(a) || [], @config) : super
212
+ end
213
+
214
+ def to_html
215
+ super(:archives, @config)
216
+ end
217
+ alias :to_s to_html
218
+ alias :archive archives
219
+ end
220
+
221
+ class Article < Hash
222
+ include Template
223
+
224
+ def initialize obj, config = {}
225
+ @obj, @config = obj, config
226
+ self.load if obj.is_a? Hash
227
+ end
228
+
229
+ def load
230
+ data = if @obj.is_a? String
231
+ meta, self[:body] = File.read(@obj).split(/\n\n/, 2)
232
+
233
+ # use the date from the filename, or else toto won't find the article
234
+ @obj =~ /\/(\d{4}-\d{2}-\d{2})[^\/]*$/
235
+ ($1 ? {:date => $1} : {}).merge(YAML.load(meta))
236
+ elsif @obj.is_a? Hash
237
+ @obj
238
+ end.inject({}) {|h, (k,v)| h.merge(k.to_sym => v) }
239
+
240
+ self.taint
241
+ self.update data
242
+ self[:date] = Date.parse(self[:date].gsub('/', '-')) rescue Date.today
243
+ self
244
+ end
245
+
246
+ def [] key
247
+ self.load unless self.tainted?
248
+ super
249
+ end
250
+
251
+ def slug
252
+ self[:slug] || self[:title].slugize
253
+ end
254
+
255
+ def summary length = nil
256
+ config = @config[:summary]
257
+ sum = if self[:body] =~ config[:delim]
258
+ self[:body].split(config[:delim]).first
259
+ else
260
+ self[:body].match(/(.{1,#{length || config[:length] || config[:max]}}.*?)(\n|\Z)/m).to_s
261
+ end
262
+ markdown(sum.length == self[:body].length ? sum : sum.strip.sub(/\.\Z/, '&hellip;'))
263
+ end
264
+
265
+ def url
266
+ "http://#{(@config[:url].sub("http://", '') + self.path).squeeze('/')}"
267
+ end
268
+ alias :permalink url
269
+
270
+ def body
271
+ markdown self[:body].sub(@config[:summary][:delim], '') rescue markdown self[:body]
272
+ end
273
+
274
+ def path
275
+ "/#{@config[:prefix]}#{self[:date].strftime("/%Y/%m/%d/#{slug}/")}".squeeze('/')
276
+ end
277
+
278
+ def title() self[:title] || "an article" end
279
+ def date() @config[:date].call(self[:date]) end
280
+ def author() self[:author] || @config[:author] end
281
+ def color() self[:color] end
282
+ def to_html() self.load; super(:article, @config) end
283
+ alias :to_s to_html
284
+ end
285
+
286
+ class Config < Hash
287
+ Defaults = {
288
+ :author => ENV['USER'], # blog author
289
+ :title => Dir.pwd.split('/').last, # site title
290
+ :root => "index", # site index
291
+ :url => "http://127.0.0.1", # root URL of the site
292
+ :prefix => "", # common path prefix for the blog
293
+ :date => lambda {|now| now.strftime("%d/%m/%Y") }, # date function
294
+ :markdown => :smart, # use markdown
295
+ :disqus => false, # disqus name
296
+ :summary => {:max => 150, :delim => /~\n/}, # length of summary and delimiter
297
+ :ext => 'txt', # extension for articles
298
+ :cache => 28800, # cache duration (seconds)
299
+ :github => {:user => "", :repos => [], :ext => 'md'}, # Github username and list of repos
300
+ :to_html => lambda {|path, page, ctx| # returns an html, from a path & context
301
+ ERB.new(File.read("#{path}/#{page}.rhtml")).result(ctx)
302
+ },
303
+ :error => lambda {|code| # The HTML for your error page
304
+ "<font style='font-size:300%'>toto, we're not in Kansas anymore (#{code})</font>"
305
+ }
306
+ }
307
+ def initialize obj
308
+ self.update Defaults
309
+ self.update obj
310
+ end
311
+
312
+ def set key, val = nil, &blk
313
+ if val.is_a? Hash
314
+ self[key].update val
315
+ else
316
+ self[key] = block_given?? blk : val
317
+ end
318
+ end
319
+ end
320
+
321
+ class Server
322
+ attr_reader :config, :site
323
+
324
+ def initialize config = {}, &blk
325
+ @config = config.is_a?(Config) ? config : Config.new(config)
326
+ @config.instance_eval(&blk) if block_given?
327
+ @site = Toto::Site.new(@config)
328
+ end
329
+
330
+ def call env
331
+ @request = Rack::Request.new env
332
+ @response = Rack::Response.new
333
+
334
+ return [400, {}, []] unless @request.get?
335
+
336
+ path, mime = @request.path_info.split('.')
337
+ route = (path || '/').split('/').reject {|i| i.empty? }
338
+
339
+ response = @site.go(route, env, *(mime ? mime : []))
340
+
341
+ @response.body = [response[:body]]
342
+ @response['Content-Length'] = response[:body].bytesize.to_s unless response[:body].empty?
343
+ @response['Content-Type'] = Rack::Mime.mime_type(".#{response[:type]}")
344
+
345
+ # Set http cache headers
346
+ @response['Cache-Control'] = if Toto.env == 'production'
347
+ "public, max-age=#{@config[:cache]}"
348
+ else
349
+ "no-cache, must-revalidate"
350
+ end
351
+
352
+ @response['ETag'] = %("#{Digest::SHA1.hexdigest(response[:body])}")
353
+
354
+ @response.status = response[:status]
355
+ @response.finish
356
+ end
357
+ end
358
+ end
359
+