cartera-toto 0.4.5

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/.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,31 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "cartera-toto"
8
+ gem.summary = %Q{the tiniest blog-engine in Oz}
9
+ gem.description = %Q{the tiniest blog-engine in Oz.}
10
+ gem.email = "cartera@opt-6.com"
11
+ gem.homepage = "http://github.com/cartera/toto"
12
+ gem.authors = ["cloudhead, cartera"]
13
+ gem.add_development_dependency "riot"
14
+ gem.add_dependency "builder"
15
+ gem.add_dependency "rack"
16
+ gem.add_dependency "rdiscount"
17
+ end
18
+ Jeweler::GemcutterTasks.new
19
+ rescue LoadError
20
+ puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
21
+ end
22
+
23
+ require 'rake/testtask'
24
+ Rake::TestTask.new(:test) do |test|
25
+ test.libs << 'lib' << 'test'
26
+ test.pattern = 'test/**/*_test.rb'
27
+ test.verbose = true
28
+ end
29
+
30
+ task :test => :check_dependencies
31
+ task :default => :test
data/TODO ADDED
@@ -0,0 +1,2 @@
1
+ TODO
2
+ ====
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.4.5
data/lib/ext/ext.rb ADDED
@@ -0,0 +1,46 @@
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
+ end
18
+
19
+ class Fixnum
20
+ def ordinal
21
+ # 1 => 1st
22
+ # 2 => 2nd
23
+ # 3 => 3rd
24
+ # ...
25
+ case self % 100
26
+ when 11..13; "#{self}th"
27
+ else
28
+ case self % 10
29
+ when 1; "#{self}st"
30
+ when 2; "#{self}nd"
31
+ when 3; "#{self}rd"
32
+ else "#{self}th"
33
+ end
34
+ end
35
+ end
36
+ end
37
+
38
+ class Date
39
+ # This check is for people running Toto with ActiveSupport, avoid a collision
40
+ unless respond_to? :iso8601
41
+ # Return the date as a String formatted according to ISO 8601.
42
+ def iso8601
43
+ ::Time.utc(year, month, day, 0, 0, 0, 0).iso8601
44
+ end
45
+ end
46
+ end
data/lib/toto.rb ADDED
@@ -0,0 +1,351 @@
1
+ require 'yaml'
2
+ require 'date'
3
+ require 'erb'
4
+ require 'rack'
5
+ require 'digest'
6
+ require 'open-uri'
7
+
8
+ require 'rdiscount'
9
+ require 'builder'
10
+
11
+ $:.unshift File.dirname(__FILE__)
12
+
13
+ require 'ext/ext'
14
+
15
+ module Toto
16
+ Paths = {
17
+ :templates => "templates",
18
+ :pages => "templates/pages",
19
+ :articles => "articles"
20
+ }
21
+
22
+ def self.env
23
+ ENV['RACK_ENV'] || 'production'
24
+ end
25
+
26
+ def self.env= env
27
+ ENV['RACK_ENV'] = env
28
+ end
29
+
30
+ module Template
31
+ def to_html page, config, &blk
32
+ path = ([:layout, :repo].include?(page) ? Paths[:templates] : Paths[:pages])
33
+ config[:to_html].call(path, page, binding)
34
+ end
35
+
36
+ def markdown text
37
+ if (options = @config[:markdown])
38
+ Markdown.new(text.to_s.strip, *(options.eql?(true) ? [] : options)).to_html
39
+ else
40
+ text.strip
41
+ end
42
+ end
43
+
44
+ def method_missing m, *args, &blk
45
+ self.keys.include?(m) ? self[m] : super
46
+ end
47
+
48
+ def self.included obj
49
+ obj.class_eval do
50
+ define_method(obj.to_s.split('::').last.downcase) { self }
51
+ end
52
+ end
53
+ end
54
+
55
+ class Site
56
+ def initialize config
57
+ @config = config
58
+ end
59
+
60
+ def [] *args
61
+ @config[*args]
62
+ end
63
+
64
+ def []= key, value
65
+ @config.set key, value
66
+ end
67
+
68
+ def index type = :html
69
+ articles = type == :html ? self.articles.reverse : self.articles
70
+ {:articles => articles.map do |article|
71
+ Article.new article, @config
72
+ end}.merge archives
73
+ end
74
+
75
+ def archives filter = ""
76
+ entries = ! self.articles.empty??
77
+ self.articles.select do |a|
78
+ filter !~ /^\d{4}/ || File.basename(a) =~ /^#{filter}/
79
+ end.reverse.map do |article|
80
+ Article.new article, @config
81
+ end : []
82
+
83
+ return :archives => Archives.new(entries, @config)
84
+ end
85
+
86
+ def article route
87
+ Article.new("#{Paths[:articles]}/#{route.join('-')}.#{self[:ext]}", @config).load
88
+ end
89
+
90
+ def /
91
+ self[:root]
92
+ end
93
+
94
+ def go route, type = :html
95
+ route << self./ if route.empty?
96
+ type, path = type =~ /html|xml|json/ ? type.to_sym : :html, route.join('/')
97
+ context = lambda do |data, page|
98
+ Context.new(data, @config, path).render(page, type)
99
+ end
100
+
101
+ body, status = if Context.new.respond_to?(:"to_#{type}")
102
+ if route.first =~ /\d{4}/
103
+ case route.size
104
+ when 1..3
105
+ context[archives(route * '-'), :archives]
106
+ when 4
107
+ context[article(route), :article]
108
+ else http 400
109
+ end
110
+ elsif respond_to?(path)
111
+ context[send(path, type), path.to_sym]
112
+ elsif (repo = @config[:github][:repos].grep(/#{path}/).first) &&
113
+ !@config[:github][:user].empty?
114
+ context[Repo.new(repo, @config), :repo]
115
+ else
116
+ context[{}, path.to_sym]
117
+ end
118
+ else
119
+ http 400
120
+ end
121
+
122
+ rescue Errno::ENOENT => e
123
+ return :body => http(404).first, :type => :html, :status => 404
124
+ else
125
+ return :body => body || "", :type => type, :status => status || 200
126
+ end
127
+
128
+ protected
129
+
130
+ def http code
131
+ [@config[:error].call(code), code]
132
+ end
133
+
134
+ def articles
135
+ self.class.articles self[:ext]
136
+ end
137
+
138
+ def self.articles ext
139
+ Dir["#{Paths[:articles]}/*.#{ext}"].sort_by {|entry| File.basename(entry) }
140
+ end
141
+
142
+ class Context
143
+ include Template
144
+
145
+ def initialize ctx = {}, config = {}, path = "/"
146
+ @config, @context, @path = config, ctx, path
147
+ @articles = Site.articles(@config[:ext]).reverse.map do |a|
148
+ Article.new(a, @config)
149
+ end
150
+
151
+ ctx.each do |k, v|
152
+ meta_def(k) { ctx.instance_of?(Hash) ? v : ctx.send(k) }
153
+ end
154
+ end
155
+
156
+ def title
157
+ @config[:title]
158
+ end
159
+
160
+ def render page, type
161
+ content = to_html page, @config
162
+ type == :html ? to_html(:layout, @config, &Proc.new { content }) : send(:"to_#{type}", page)
163
+ end
164
+
165
+ def to_xml page
166
+ xml = Builder::XmlMarkup.new(:indent => 2)
167
+ instance_eval File.read("#{Paths[:templates]}/#{page}.builder")
168
+ end
169
+ alias :to_atom to_xml
170
+
171
+ def method_missing m, *args, &blk
172
+ @context.respond_to?(m) ? @context.send(m, *args, &blk) : super
173
+ end
174
+ end
175
+ end
176
+
177
+ class Repo < Hash
178
+ include Template
179
+
180
+ README = "http://github.com/%s/%s/raw/master/README.%s"
181
+
182
+ def initialize name, config
183
+ self[:name], @config = name, config
184
+ end
185
+
186
+ def readme
187
+ markdown open(README %
188
+ [@config[:github][:user], self[:name], @config[:github][:ext]]).read
189
+ rescue Timeout::Error, OpenURI::HTTPError => e
190
+ "This page isn't available."
191
+ end
192
+ alias :content readme
193
+ end
194
+
195
+ class Archives < Array
196
+ include Template
197
+
198
+ def initialize articles, config
199
+ self.replace articles
200
+ @config = config
201
+ end
202
+
203
+ def [] a
204
+ a.is_a?(Range) ? self.class.new(self.slice(a) || [], @config) : super
205
+ end
206
+
207
+ def to_html
208
+ super(:archives, @config)
209
+ end
210
+ alias :to_s to_html
211
+ alias :archive archives
212
+ end
213
+
214
+ class Article < Hash
215
+ include Template
216
+
217
+ def initialize obj, config = {}
218
+ @obj, @config = obj, config
219
+ self.load if obj.is_a? Hash
220
+ end
221
+
222
+ def load
223
+ data = if @obj.is_a? String
224
+ meta, self[:body] = File.read(@obj).split(/\n\n/, 2)
225
+
226
+ # use the date from the filename, or else toto won't find the article
227
+ @obj =~ /\/(\d{4}-\d{2}-\d{2})[^\/]*$/
228
+ ($1 ? {:date => $1} : {}).merge(YAML.load(meta))
229
+ elsif @obj.is_a? Hash
230
+ @obj
231
+ end.inject({}) {|h, (k,v)| h.merge(k.to_sym => v) }
232
+
233
+ self.taint
234
+ self.update data
235
+ self[:date] = Date.parse(self[:date].gsub('/', '-')) rescue Date.today
236
+ self
237
+ end
238
+
239
+ def [] key
240
+ self.load unless self.tainted?
241
+ super
242
+ end
243
+
244
+ def slug
245
+ self[:slug] || self[:title].slugize
246
+ end
247
+
248
+ def summary length = nil
249
+ config = @config[:summary]
250
+ sum = if self[:body] =~ config[:delim]
251
+ self[:body].split(config[:delim]).first
252
+ else
253
+ self[:body].match(/(.{1,#{length || config[:length] || config[:max]}}.*?)(\n|\Z)/m).to_s
254
+ end
255
+ markdown(sum.length == self[:body].length ? sum : sum.strip.sub(/\.\Z/, '&hellip;'))
256
+ end
257
+
258
+ def url
259
+ "http://#{(@config[:url].sub("http://", '') + self.path).squeeze('/')}"
260
+ end
261
+ alias :permalink url
262
+
263
+ def body
264
+ markdown self[:body].sub(@config[:summary][:delim], '') rescue markdown self[:body]
265
+ end
266
+
267
+ def path
268
+ "/#{@config[:prefix]}#{self[:date].strftime("/%Y/%m/%d/#{slug}/")}".squeeze('/')
269
+ end
270
+
271
+ def title() self[:title] || "an article" end
272
+ def date() @config[:date].call(self[:date]) end
273
+ def author() self[:author] || @config[:author] end
274
+ def to_html() self.load; super(:article, @config) end
275
+ alias :to_s to_html
276
+ end
277
+
278
+ class Config < Hash
279
+ Defaults = {
280
+ :author => ENV['USER'], # blog author
281
+ :title => Dir.pwd.split('/').last, # site title
282
+ :root => "index", # site index
283
+ :url => "http://127.0.0.1", # root URL of the site
284
+ :prefix => "", # common path prefix for the blog
285
+ :date => lambda {|now| now.strftime("%d/%m/%Y") }, # date function
286
+ :markdown => :smart, # use markdown
287
+ :disqus => false, # disqus name
288
+ :summary => {:max => 150, :delim => /~\n/}, # length of summary and delimiter
289
+ :ext => 'txt', # extension for articles
290
+ :cache => 28800, # cache duration (seconds)
291
+ :github => {:user => "", :repos => [], :ext => 'md'}, # Github username and list of repos
292
+ :to_html => lambda {|path, page, ctx| # returns an html, from a path & context
293
+ ERB.new(File.read("#{path}/#{page}.rhtml")).result(ctx)
294
+ },
295
+ :error => lambda {|code| # The HTML for your error page
296
+ "<font style='font-size:300%'>toto, we're not in Kansas anymore (#{code})</font>"
297
+ }
298
+ }
299
+ def initialize obj
300
+ self.update Defaults
301
+ self.update obj
302
+ end
303
+
304
+ def set key, val = nil, &blk
305
+ if val.is_a? Hash
306
+ self[key].update val
307
+ else
308
+ self[key] = block_given?? blk : val
309
+ end
310
+ end
311
+ end
312
+
313
+ class Server
314
+ attr_reader :config, :site
315
+
316
+ def initialize config = {}, &blk
317
+ @config = config.is_a?(Config) ? config : Config.new(config)
318
+ @config.instance_eval(&blk) if block_given?
319
+ @site = Toto::Site.new(@config)
320
+ end
321
+
322
+ def call env
323
+ @request = Rack::Request.new env
324
+ @response = Rack::Response.new
325
+
326
+ return [400, {}, []] unless @request.get?
327
+
328
+ path, mime = @request.path_info.split('.')
329
+ route = (path || '/').split('/').reject {|i| i.empty? }
330
+
331
+ response = @site.go(route, *(mime ? mime : []))
332
+
333
+ @response.body = [response[:body]]
334
+ @response['Content-Length'] = response[:body].length.to_s unless response[:body].empty?
335
+ @response['Content-Type'] = Rack::Mime.mime_type(".#{response[:type]}")
336
+
337
+ # Set http cache headers
338
+ @response['Cache-Control'] = if Toto.env == 'production'
339
+ "public, max-age=#{@config[:cache]}"
340
+ else
341
+ "no-cache, must-revalidate"
342
+ end
343
+
344
+ @response['ETag'] = Digest::SHA1.hexdigest(response[:body])
345
+
346
+ @response.status = response[:status]
347
+ @response.finish
348
+ end
349
+ end
350
+ end
351
+