Skip to content

Rails Integration Techniques

jejacks0n edited this page Jan 2, 2012 · 2 revisions

Mercury Editor can be integrated in several different ways. Typically it's as simple as wrapping your page within the Mercury layout (layouts/mercury.html.erb). The layout can optionally be installed using the install generator. The examples below are designed to help if you'd prefer not to use the /editor route, or integrate Mercury into your Rails app more seamlessly.

Cookie Technique

First let's make our top level controller (eg. ApplicationController) determine if it should load Mercury. As mentioned above, it's as simple as determining which layout we should use. We'll do that by providing a way to set a cookie and use the built in Mercury::Authentication module -- specifically the can_edit? method.

include Mercury::Authentication

Next we'll need a way to figure out if a user is editing the page or not. So let's add a method to our controller that we can use. We'll also expose this method as a helper method so it can be used in the views.

helper_method :is_editing?

def is_editing?
  cookies[:editing] == 'true' && can_edit?
end

Next we'll set a global layout using a method. In this case we'll call it layout_with_mercury. This is where we'll determine if we should load Mercury or not.

layout :layout_with_mercury

def layout_with_mercury
  # if we're not already within mercury, and the user is able, load the mercury template.
  # otherwise use the default application template.
  !params[:mercury_frame] && is_editing? ? 'mercury' : 'application'
end

You'll probably notice the params[:mercury_frame], which is always passed to the server so we know that it's Mercury requesting the page. Knowing this, we can render the standard page using the default layout (in this case application).

Let's review and put all of this together.. Here's the end result of the controller.

class ApplicationController < ActionController::Base
  protect_from_forgery

  include Mercury::Authentication

  layout :layout_with_mercury
  helper_method :is_editing?

  private

  def layout_with_mercury
    !params[:mercury_frame] && is_editing? ? 'mercury' : 'application'
  end

  def is_editing?
    cookies[:editing] == 'true' && can_edit?
  end
end

Now all we have to do is toggle that cookie. You can do this in your own way, but this is a pretty simple example of the moving parts.

<%= link_to_function "Toggle Mercury Editor", "document.cookie='editing=#{is_editing? ? 'false' : 'true'}';top.location.href=top.location.href" %>

Put that in your application layout or wherever and you're ready to go. That's it.