forked from cloudhead/toto
/
toto.rb
482 lines (389 loc) · 12.8 KB
/
toto.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
require 'yaml'
require 'date'
require 'erb'
require 'rack'
require 'digest'
require 'open-uri'
if RUBY_PLATFORM =~ /win32/
require 'maruku'
Markdown = Maruku
else
require 'rdiscount'
end
require 'builder'
$:.unshift File.dirname(__FILE__)
require 'ext/ext'
module Toto
Paths = {
:templates => "templates",
:pages => "templates/pages",
:articles => "articles"
}
def self.env
ENV['RACK_ENV'] || 'production'
end
def self.env= env
ENV['RACK_ENV'] = env
end
module Template
def to_html page, config, &blk
path = ([:layout, :repo].include?(page) ? Paths[:templates] : Paths[:pages])
config[:to_html].call(path, page, binding)
end
def markdown text
if (options = @config[:markdown])
Markdown.new(text.to_s.strip, *(options.eql?(true) ? [] : options)).to_html
else
text.strip
end
end
def method_missing m, *args, &blk
self.keys.include?(m) ? self[m] : super
end
def self.included obj
obj.class_eval do
define_method(obj.to_s.split('::').last.downcase) { self }
end
end
end
class Site
def initialize config
@config = config
end
def [] *args
@config[*args]
end
def []= key, value
@config.set key, value
end
def index type = :html
articles = type == :html ? self.articles.reverse : self.articles
{:articles => articles.map do |article|
Article.new article, @config
end}.merge archives
end
def archives opts = {}
opts = {:date => opts} unless opts.is_a?(Hash)
# entries: array of filenames
entries = self.articles || []
# filter by date
if !(filter = opts.delete(:date)).nil? and filter =~ /^\d{4}/
entries = entries.select do |filename|
File.basename(filename) =~ /^#{filter}/
end
end
# entries: array of articles
entries.reverse!.map!{ |filename| Article.new(filename, @config) }
# filter by tag
if !(tag = opts.delete(:tag)).nil?
opts[:tag] = Tag.new(tag, @config)
entries = entries.select do |article|
!article[:tags].nil? && article[:tags].find{|tag| tag.slug == opts[:tag].slug}
end
end
if !(category = opts.delete(:category)).nil?
entries = entries.select do |article|
!article[:category].nil? && article[:category] =~ /^#{category}/
end
end
opts.merge({:archives => Archives.new(entries, @config)})
end
def article path
Article.new("#{Paths[:articles]}/#{path}.#{self[:ext]}", @config).load
end
def /
self[:root]
end
def go route, env = {}, type = :html
route << self./ if route.empty?
type, path = type =~ /html|xml|json/ ? type.to_sym : :html, route.join('/')
context = lambda do |data, page|
Context.new(data, @config, path, env).render(page, type)
end
body, status = if Context.new.respond_to?(:"to_#{type}")
if path =~ /^(.+?\/)?(\d{4}\/\d{2}\/\d{2}\/[^\/]+)$/
context[article("#{$1}#{$2.tr('/', '-')}"), :article]
elsif 4 > route.size and route.first =~ /\d{4}/
context[archives(:date => route * '-'), :archives]
elsif 1 < route.size and route.first == 'category'
context[archives(:category => route.slice(1..-1) * '/'), :archives]
elsif 2 == route.size and route.first == 'tag'
context[archives(:tag => route.last), :tag]
elsif respond_to?(path)
context[send(path, type), path.to_sym]
elsif (repo = @config[:github][:repos].grep(/#{path}/).first) &&
!@config[:github][:user].empty?
context[Repo.new(repo, @config), :repo]
else
context[{}, path.to_sym]
end
else
http 400
end
rescue Errno::ENOENT => e
return :body => http(404).first, :type => :html, :status => 404
else
return :body => body || "", :type => type, :status => status || 200
end
protected
def http code
[@config[:error].call(code), code]
end
def articles
self.class.articles self[:ext]
end
def self.articles ext
Dir["#{Paths[:articles]}/**/*.#{ext}"].sort_by {|entry| File.basename(entry) }
end
class Context
include Template
attr_reader :env, :tags_cloud
def initialize ctx = {}, config = {}, path = "/", env = {}
@config, @context, @path, @env, @page_title = config, ctx, path, env, []
@articles = Site.articles(@config[:ext]).reverse.map do |a|
Article.new(a, @config)
end
@tags_cloud = TagCloud.new(@articles, @config)
ctx.each do |k, v|
meta_def(k) { ctx.instance_of?(Hash) ? v : ctx.send(k) }
end
end
def title
@config[:title]
end
def render page, type
content = to_html page, @config
type == :html ? to_html(:layout, @config, &Proc.new { content }) : send(:"to_#{type}", page)
end
def to_xml page
xml = Builder::XmlMarkup.new(:indent => 2)
instance_eval File.read("#{Paths[:templates]}/#{page}.builder")
end
alias :to_atom to_xml
def method_missing m, *args, &blk
@context.respond_to?(m) ? @context.send(m, *args, &blk) : super
end
def page_title! str
@page_title << str
str
end
def page_title
@page_title.dup
end
end
end
class Repo < Hash
include Template
README = "https://github.com/%s/%s/raw/master/README.%s"
def initialize name, config
self[:name], @config = name, config
end
def readme
markdown open(README %
[@config[:github][:user], self[:name], @config[:github][:ext]]).read
rescue Timeout::Error, OpenURI::HTTPError => e
"This page isn't available."
end
alias :content readme
end
class Archives < Array
include Template
def initialize articles, config
self.replace articles
@config = config
end
def [] a
a.is_a?(Range) ? self.class.new(self.slice(a) || [], @config) : super
end
def to_html
super(:archives, @config)
end
alias :to_s to_html
alias :archive archives
end
class Article < Hash
include Template
def initialize obj, config = {}
@obj, @config = obj, config
self.load if obj.is_a? Hash
end
def load
data = if @obj.is_a? String
meta, self[:body] = File.read(@obj).split(/\n\n/, 2)
# grab category from filename
category = File.dirname(@obj.sub(/^#{Paths[:articles]}/, '')).slice(1..-1)
# use the date from the filename, or else toto won't find the article
@obj =~ /\/(\d{4}-\d{2}-\d{2})[^\/]*$/
($1 ? {:date => $1} : {}).merge({:category => category}).merge(YAML.load(meta))
elsif @obj.is_a? Hash
@obj
end.inject({}) {|h, (k,v)| h.merge(k.to_sym => v) }
self.taint
self.update data
self[:tags] = self[:tags].to_s.split(',') unless self[:tags].is_a? Array
self[:date] = Date.parse(self[:date].gsub('/', '-')) rescue Date.today
self[:tags].map!{|str| Tag.new(str, @config)}
self
end
def [] key
self.load unless self.tainted?
super
end
def slug
self[:slug] || self[:title].slugize
end
def summary length = nil
config, links = @config[:summary], []
# grab out all link references
text = self[:body].gsub(/^\[[^\]]+\]:.+(?:\n[\t ]+.*)?/){|str| links << str; ""}
# leave only summary text
text = if text =~ config[:delim]
text.split(config[:delim]).first
else
text.match(/(.{1,#{length || config[:length] || config[:max]}}.*?)(\n|\Z)/m).to_s
end.strip
# append hellip if needed
text = text.sub(/\.\Z/, '…') if text.length < self[:body].length
# append links and markdown summary
markdown(text << "\n" << links.join("\n").strip)
end
def url
"http://#{(@config[:url].sub("http://", '') + self.path).squeeze('/')}"
end
alias :permalink url
def body
markdown self[:body].sub(@config[:summary][:delim], '') rescue markdown self[:body]
end
def path
"/#{@config[:prefix]}#{self.category}/#{self[:date].strftime("/%Y/%m/%d/#{slug}/")}".squeeze('/')
end
def title() self[:title] || "an article" end
def date() @config[:date].call(self[:date]) end
def author() self[:author] || @config[:author] end
def tags() self[:tags] end
def category() self[:category] end
def to_html() self.load; super(:article, @config) end
alias :to_s to_html
end
class Config < Hash
Defaults = {
:author => ENV['USER'], # blog author
:title => Dir.pwd.split('/').last, # site title
:root => "index", # site index
:url => "http://127.0.0.1", # root URL of the site
:prefix => "", # common path prefix for the blog
:date => lambda {|now| now.strftime("%d/%m/%Y") }, # date function
:markdown => :smart, # use markdown
:disqus => false, # disqus name
:summary => {:max => 150, :delim => /~\n/}, # length of summary and delimiter
:ext => 'txt', # extension for articles
:cache => 28800, # cache duration (seconds)
:github => {:user => "", :repos => [], :ext => 'md'}, # Github username and list of repos
:to_html => lambda {|path, page, ctx| # returns an html, from a path & context
ERB.new(File.read("#{path}/#{page}.rhtml")).result(ctx)
},
:error => lambda {|code| # The HTML for your error page
"<font style='font-size:300%'>toto, we're not in Kansas anymore (#{code})</font>"
}
}
def initialize obj
self.update Defaults
self.update obj
end
def set key, val = nil, &blk
if val.is_a? Hash
self[key].update val
else
self[key] = block_given?? blk : val
end
end
end
class Server
attr_reader :config, :site
def initialize config = {}, &blk
@config = config.is_a?(Config) ? config : Config.new(config)
@config.instance_eval(&blk) if block_given?
@site = Toto::Site.new(@config)
end
def call env
@request = Rack::Request.new env
@response = Rack::Response.new
return [400, {}, []] unless @request.get?
path, mime = @request.path_info.split('.')
route = (path || '/').split('/').reject {|i| i.empty? }
response = @site.go(route, env, *(mime ? mime : []))
@response.body = [response[:body]]
@response['Content-Length'] = response[:body].bytesize.to_s unless response[:body].empty?
@response['Content-Type'] = Rack::Mime.mime_type(".#{response[:type]}")
# Set http cache headers
@response['Cache-Control'] = if Toto.env == 'production'
"public, max-age=#{@config[:cache]}"
else
"no-cache, must-revalidate"
end
@response['ETag'] = %("#{Digest::SHA1.hexdigest(response[:body])}")
@response.status = response[:status]
@response.finish
end
end
class Tag
attr_reader :title, :slug
def initialize title, config = {}
@config = config
@title = title.strip
@slug = Tag.slugize(@title)
end
def to_s
@slug
end
def url
"http://#{(@config[:url].sub("http://", '') + self.path).squeeze('/')}"
end
alias :permalink url
def path
"/#{@config[:prefix]}tag/#{@slug}"
end
def self.slugize obj
obj.to_s.strip.slugize
end
end
class TagCloud < Hash
class Nube < Tag
attr_accessor :count, :weight
def initialize tag, config
@count, @weight = 1, 0
super tag.title, config
end
end
def initialize articles, config = {}
# fill-in tags
articles.each do |article|
article.tags.each do |tag|
unless self[tag.slug].nil?
self[tag.slug].count += 1
else
self[tag.slug] = Nube.new(tag, config)
end
end
end
# get min/max bounds
cnt = self.values.collect{|nube| nube.count}
min = cnt.min.to_i
max = cnt.max.to_i
# get correction rate
rate = (max - min) / 9 + 1
# calculate weight
self.each_value {|nube| nube.weight = (nube.count - min) / rate}
end
def [] key
super Tag.slugize(key)
end
def snowball
ball, ops = [], [:push, :unshift]
self.values.sort!{|a,b| b.count <=> a.count}.each do |nube|
ball.send ops.rotate!.first, nube
end
ball
end
end
end