Last active
December 31, 2015 08:59
-
-
Save pixeltrix/7964427 to your computer and use it in GitHub Desktop.
Lightweight template rendering for rake tasks, background jobs, etc. using Tilt template engine.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Feed URLs need to be explict passed as options because there is no request object | |
atom_feed( | |
id: "tag:weblog.rubyonrails.org,2005:/feed/atom", | |
root_url: "http://weblog.rubyonrails.org/", | |
url: "http://weblog.rubyonrails.org/feed/atom.xml" | |
) do |feed| | |
feed.title("Riding Rails") | |
feed.updated(@posts.first.updated_at) | |
@posts.each do |post| | |
feed.entry(post, | |
id: "tag:weblog.rubyonrails.org,2005:#{post_path(post)}", | |
url: "http://weblog.rubyonrails.org#{post_path(post)}" | |
) do |entry| | |
entry.title(post.title) | |
entry.content(post.body, type: 'html') | |
entry.author do |author| | |
author.name("DHH") | |
end | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'builder' | |
require 'tilt' | |
# NOTE: if your view contains calls to `render` or anything request related | |
# it will probably blow up. This can be worked around by overriding both | |
# `render` and `request` in the anonymous context class. Also rendering | |
# forms for caching will probably fail due to invalid CSRF tokens. This can | |
# also be worked around by disabling the CSRF token in the form and then | |
# adding it back by submitting via an $.ajax request. | |
context = Class.new do | |
include ActionView::Helpers | |
include Rails.application.routes.url_helpers | |
# Additional application helper modules can go here | |
# Sets up instance variables for the template | |
def initialize(assigns = {}) | |
assigns.each{ |key, value| instance_variable_set(:"@#{key}", value) } | |
end | |
protected | |
# Needed if you want to use *_url helper methods | |
def default_url_options | |
{ host: 'weblog.rubyonrails.org' } | |
end | |
end | |
template = Tilt.new("atom.xml.builder") | |
output = template.render(context.new(posts: Post.feed)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment