I want to have a rake task that reads a HAML file and creates a static html file out of it. The reason for this is that I want to dynamically localize my error pages in a manner described here http://devcorner.mynewsdesk.com/2010/01/13/rails-i18n-and-404500-error-pages/
Here is the method for writing the error pages.
def write_error_page(status, locale = nil)
dest_filename = [status.to_s, locale, "html"].compact.join(".")
File.open(File.join(Rails.root, "public", dest_filename), "w") do |file|
path = File.join(Rails.root, "app", "views", "errors", "#{status}.haml")
file.print Haml::Engine.new(File.read(path)).render
end
end
The problem is that Haml::Engine does not have rails methods available. So when a try to read the haml file, I get an error for every rails method in the file (I want to use methods
like image_tag, form_for and obviously I18n.translate).
I noticed a similar issue that had been solved here: Rails HAML engine rendering
However, when I try the solution mentioned in the link above, I get the following error: “undefined local variable or method `config’ for #”.
How could I get the rails methods to work in the Haml::Engine so that I could read the HAML file? I also tried switching to ERB, but noticed that it leads to the same problem, which somebody else has at least partially resolved here render erb from database into view problem please help! But this solution didn’t help me either.
I’m also open to other solutions than using Haml::Engine. I looked into capture_haml helper but don’t see how that would help me either.
I just now realized that I don’t need Haml::Engine in this situation, because I’m in a rails environment so I can just call render. Silly me.
However, it’s not completely trivial to call render from a rake task, because we are not in a controller or a view (and so rails purists even say that you should never do so, I think, but in this case it seems like the easiest way), so I post the code I used here (I used the approach mentioned here: http://wholemeal.co.nz/blog/2011/04/05/rendering-from-a-model-in-rails-3/).
I had some problems with this approach too. For instance, form_for still didn’t work properly (I want to have a feedback form on the error page) so I simply created the form with plain HTML (which you can luckily inject straight into .haml files). But the one thing from rails I needed to get to work in the .haml template – method I18n.translate – works like charm.