Create custom rake tasks in Webby
I love Webby. I use it quite often these days (here are just two of the many examples: 1 and 2). It’s so fast and very easy to deploy.
Just recently I chose Webby for a documentation site. It has FAQs and help articles/tutorials. Basic stuff. For each entry, I wanted to have a structure something like this:
doc_project |_ content | |_ entries | |_ 1.txt | |_ 2.txt |_ images |_ 1 |_ 2
(Sorry for the poor attempt at illustrating a directory structure)
Essentially, I wanted to keep all the *.txt files in a entries/ (or whatever) directory, and have a special nested directory in images/ that matched the name of the txt file. For documentation sites, I find that keeping a structure like that helps with screenshots and such. It more or less creates a namespace to prevent file clashing.
Since we programmers don’t like to do things manually, I took advantage of Webby’s support for custom rake tasks. So now I can run:
1 | rake create:entry "This is the title of the new entry" |
And it will handle this for me. Here’s the task:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | namespace :create do desc "Creates a new Doc entry" task :entry do |t| page, title, dir = Webby::Builder.new_page_info dir = File.join(dir, "entries") entry_count = Dir["#{dir}/*"].collect { |f| File.directory?(f) }.size new_page_name = "#{entry_count + 1}" page = File.join(dir, new_page_name) Dir.mkdir("#{Webby.site.content_dir}/images/#{new_page_name}") page = Webby::Builder.create(page, :from => "#{Webby.site.template_dir}/entries/entry.erb", :locals => { :title => title, :directory => dir }) Webby.exec_editor(page) end end |
I have a pre-defined template in doc_project/templates/entries/entry.erb that my new files are based off of (notice the :from option in the call to Webby::Builder.create(...)).
I would break down the rake task, but I think it’s self-explanatory. The only piece that’s not obvious is the :locals option. And that just makes variables available in your templates (so I can have the title automatically filled in, for example).
Overall, Webby is awesome by itself and doesn’t need any additional support. But even so, now you know how to tell it to do a bit more.
