I wanted PetersBlogger to have a preview facility when composing posts that would automatically run the text I was editing through my wilki filter as I typed and give me a live preview of how the post would turn out when it was formatted and displayed. No pressing a preview button for me, I wanted it to just happen. Sounds like a job for AJAX. But how to do this in rails? Well it turns out to be very easy.
I put this in my form where I edit a post:
<p><%= f.text_area 'body', :size => "100x40", :html => { :id => :body} %></p> <%= observe_field :post_body, :url => { :action => :wilkify }, :frequency => 3.00, :update => :preview, :with => "'text='+escape( $('post_body').value)" %> <div id="preview"/>
This puts some javascript in the page that monitors the text_area where I am editing and, if it changes it will invoke the 'wilkify' action in my controller, passing it what I have typed thus far.
The 'wilkify' action is very simple, it just gets the text, wilkifies it and makes sure it is rendered as a simple piece of html, without the main site layout:
def wilkify strBody = params[:text] strBody = CGI::unescape( strBody) @text = Wilki( strBody) render :layout => false end
I have a small view defined to wrap the preview text in a couple of div's, just as if they were appearing on the site:
<div class="node"> <div class="bodynode"> <div class="entry"> <%= @text %> </div> </div> </div>
The wikified text is then inserted into the edit form in the div with the id 'preview'.
I have to add the prototype javascript library to the head section of the main application layout:
<%= javascript_include_tag 'prototype' %>
It is not entirely perfect and I would never let strangers use it because they could type malformed html and totally mess things up but it is good enough for me.


Watch out, Microsoft might throw a chair at you for patent infringement patentstorm.us/patents/7231602.html