Sunday, December 5, 2010

Providing markdown engine options in HAML

I've started looking into using Markdown in Rails. I use HAML for rendering views, so markdown is handled by a HAML filter:

%h1 Here's some rendered Markdown
  :markdown
    = @model.markdown

This worked great, but I was concerned about javascript injection since the markdown would be provided by a user using a WMD editor. I found that I could explicitly call RDiscount, with the :filter_html option, to render the markdown myself:

%h1 Here's some rendered Markdown
  != RDiscount.new(@model.markdown, :filter_html).to_html

This worked great, but I didn't want to have to remember this incantation every time I want to render some Markdown. After some discussion with Nathan Weizenbaum the current maintainer of Haml, I realized that the answer is actually presented (somewhat indirectly) through the documentation. The section on Custom Filters says "You can also define your own filters. See Haml::Filters for details.". You have to then follow on to Haml::Filters::Base for the full story.

In my Rails app, I created a custom Haml filter that overrides the original :markdown (so I don't accidentally forget and use an unsafe :markdown) config/initializers/haml.rb:

module MyApp
  module Filters
    module Markdown
      include Haml::Filters::Base
      lazy_require 'rdiscount'

      def render(text)
        ::RDiscount.new(text, :filter_html).to_html
      end
    end
  end
end

Now, whenever HAML renders a :markdown filter, it will filter the HTML and protect me against javascript injection attacks.

Thursday, December 2, 2010

Stop deploying unneccessary Gems in your Heroku slug

Heroku published a handy tip in their newsletter today:
$ heroku config:add BUNDLE_WITHOUT=development:test
Having set this and pushed a change to my Gemfile, my slug size went from 39.4MB down to 10.9MB.

Smaller slugs compile and load faster.

Thank you Heroku!

Monday, November 22, 2010

Rake duplicate task descriptions

Using Rake I can define tasks that get added to a collection of tasks for execution.  For example:
desc "one"
task :one do
  puts "one"
end

desc "all"
task :all => [:one]

desc "two"
task :two do
  puts "two"
end

desc "all"
task :all => [:two]

Now, if I look at rake --tasks I will see:
> rake --tasks
rake one     # one
rake two     # two
rake all     # all / all

Rake has duplicated the description for the :all task. Looking at the code for Rake I discovered that this can be avoided by terminating the :all task description with a period:
desc "one"
desc "all."
task :all => [:one]

desc "one"
desc "all."
task :all => [:one]

> rake --tasks
rake one     # one
rake two     # two
rake all     # all.