Skip to content

Instantly share code, notes, and snippets.

@stonegao
Forked from pjb3/haml_in_effigy.rb
Created December 22, 2009 11:13
Show Gist options
  • Save stonegao/261680 to your computer and use it in GitHub Desktop.
Save stonegao/261680 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'haml'
require 'effigy'
require 'effigy/core_ext/hash'
template = Haml::Engine.new(%{%html
%head
%title
%body
%h1
%p.body
.comment
%h2
%p
%a View more
%p{:id => "no-comments"} There aren't any comments for this post.
}).render
class PostView < Effigy::View
attr_reader :post
def initialize(post)
@post = post
end
def transform
text('h1', post.title)
text('title', "#{post.title} - Site title")
text('p.body', post.body)
replace_each('.comment', post.comments) do |comment|
text('h2', comment.title)
text('p', comment.summary)
attr('a', :href => url_for(comment))
end
remove('#no-comments') if post.comments.empty?
end
def url_for(comment)
"/comments/#{comment.id}"
end
end
Comment = Struct.new(:id, :title, :summary)
Post = Struct.new(:title, :body, :comments)
post = Post.new("Post title", "Post body", [])
post.comments << Comment.new(1, "First comment title", "First comment body")
post.comments << Comment.new(2, "Second comment title", "Second comment body")
view = PostView.new(post)
puts view.render(template)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment