Skip to content

Instantly share code, notes, and snippets.

@AhmedNadar
Forked from levity/photo_essay.rb
Created September 2, 2013 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AhmedNadar/6409591 to your computer and use it in GitHub Desktop.
Save AhmedNadar/6409591 to your computer and use it in GitHub Desktop.
Ruby: photo assay
#!/usr/bin/ruby
require 'yaml'
# DATA is a little-used feature of the Ruby language; it's a file handle
# whose contents are everything in the current file after the __END__.
# YAML is "Yet Another Markup Language".
data = YAML.load(DATA)
def url_for(entry_num)
"/photo_essay/#{entry_num}.html"
end
data[:entries].each_with_index do |entry, index|
index += 1 # start from entry 1 instead of 0
# treat any word in the template surrounded by double curly brackets
# as a substitution variable. there are more full-fledged templating
# libraries, e.g. Liquid, but I wanted to keep this simple.
output = data[:template].gsub(/\{\{(\w+)\}\}/) do |match|
# $1 is the first matching group; you would also have $2, $3, etc.
# if the regex had more matching groups.
case $1
when "next_url"
url_for(index == data[:entries].size ? 1 : index + 1)
else
entry[$1]
end
end
puts "entry #{index}"
puts output
# to save files:
# open("#{index + 1}.html", "w") {|file| file.write(output) }
end
__END__
:entries:
-
photo: foo.jpg
blurb: this is a very short blurb
-
photo: bar.jpg
blurb:
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
-
photo: baz.jpg
blurb: hmm hmm hmm
:template:
<div class="entry">
<img src="{{photo}}"/>
<div class="blurb">
{{blurb}}
</div>
<a href="{{next_url}}">next entry</a>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment