April 5, 2015

WYSIWYG content preview with Ruby on Rails

WYSIWYG content preview with Ruby on Rails.

In several of our projects we’ve needed to generate content previews so that our clients can edit content (we use Textile for markup) and see the results. We’ve used WYSIWYG editors in the past, but even when using third party editors we’ve just found that that effort to maintain these and still produce consistent HTML is too high for many projects - it is a sad state of affairs, but that is just how it is.

The goal is to add a ‘preview’ button so that a user can see in realtime in a separate window the content that they are generating via their edits. In order to do this we want to build a ‘fake’ version of the model we are editing with the current form content and then render it. There are several different ways to go about this of course, but we chose to push a serialized version of the form to the preview window and then use that to render the preview.

NOTE: There are some pretty obvious security implications to the method we are using here (you can instantiate any model in the system). We generally use this with whitelisting of attributes and models - this example is slightly simplified.

  1. We create a link in the form to open up a preview window.
  1. The JS on click opens up a new window and serializes the current form to another form in the preview window. The preview window submits this form to the preview controller.
  1. The preview form takes the serialized model, creates a new model object from it and then renders the preview template.

On every keydown in the preview form (debounced) we resubmit the preview to update it.