light_blog hg clone http://hg.clarus.me/light_blog
view light_blog.rb @ 44:55bdb2143414
Article 'LightBlog le moteur de blogs léger'
| author | Guillaume Claret <guillaume@claret.me> |
|---|---|
| date | Mon Dec 12 18:33:26 2011 +0100 (5 months ago) |
| parents | 76c79d1a8424 |
| children |
line source
1 require 'erb'
2 include ERB::Util
4 # Models
5 class Blog
6 attr_reader :title, :url, :disqus, :posts
8 def initialize(title, url, disqus)
9 @title, @url, @disqus = title, url, disqus
10 @posts = []
11 Dir.foreach("posts") do |file_name|
12 if File.extname(file_name) == ".html"
13 @posts << Post.new(File.basename(file_name, ".html"))
14 end
15 end
16 @posts.sort! {|a, b| - (a.date <=> b.date)}
17 end
18 end
20 class Post
21 attr_reader :name, :date, :content, :url
23 def initialize(name)
24 file_name = "posts/#{name}.html"
25 if /\A(\d+)-(\d+)-(\d+)\s*(.*)\z/ === name
26 @date = Time.local($1, $2, $3)
27 @name = $4
28 else
29 @date = Time.at(0)
30 @name = name
31 end
32 @content = File.read(file_name)
33 @url = "#{@name}.html"
34 end
35 end
37 # Views
38 class Template
39 def initialize(file_name)
40 @erb = ERB.new(File.read("templates/#{file_name}"))
41 end
43 def result(binding)
44 @erb.result(binding).gsub(/^\s*$\n/, "").chomp
45 end
46 end
48 module Helpers
49 def header(blog, title, active_link)
50 Template.new("header.rhtml").result(binding)
51 end
53 def footer
54 Template.new("footer.rhtml").result(binding)
55 end
57 def date(time)
58 Template.new("date.rhtml").result(binding)
59 end
60 end
62 class View
63 include Helpers
64 attr_reader :url, :html
65 end
67 class PageView < View
68 def initialize(blog, file_name)
69 extension = File.extname(file_name)
70 @url = "#{File.basename(file_name, extension)}.#{extension[2..-1]}"
71 @html = Template.new(file_name).result(binding)
72 end
73 end
75 class PostView < View
76 def initialize(blog, post)
77 @url = post.url
78 @html = Template.new("post.rhtml").result(binding)
79 end
80 end
82 # Controller
83 class Controller
84 def initialize(blog)
85 @blog = blog
86 end
88 def make
89 pages = ["index.rhtml", "posts.rhtml", "links.rhtml", "about.rhtml", "rss.rxml"]
90 page_views = pages.collect {|file_name| PageView.new(@blog, file_name)}
91 post_views = @blog.posts.collect {|post| PostView.new(@blog, post)}
93 (page_views + post_views).each do |view|
94 File.open("blog/#{view.url}", "w") {|f| f << view.html}
95 end
96 end
97 end
99 # Run
100 Controller.new(Blog.new(*ARGV)).make
