119 Labs LLC

Ideas on Technology

Rails Custom Formats With Bookmarklets

I’m working on an app that makes heavy use of bookmarklets. There are some really great resources already for creating your one bookmarklets. For more information look herehere, or just search the web. One of the issues I’ve had to deal with is that many of my bookmarklet screens are using standard parts of my site just in a slightly different format.  Rather than duplicating controller logic or adding if statements everywhere I decided to add bookmarklets as a declared format. The First step was to setup my custom format.  For me it was really just an alias for js (html might work better for you in your app). So I started by creating an initializer to setup the type alias:   Make sure to restart rails server in order to see this change. Now if we visit a regular page and add the format like this http://localhost:3000/user_sessions/new.bookmarklet You should see a template missing error.  Add the file user_sessions/new.bookmarklet.erb and you should see your custom response. Now at this point you can create different template files accommodating for your different view size, layout, etc. Still in order to drive this change you need to hard code the format in to the views which are posting/linking to your custom views. In order to DRY that up I added a before filter to automatically infer the format based upon referrer.     Here I use the bookmarklet_url, which is my base path as the test whether I should be formatting for embedding in the bookmarklet or not. From here any action that I call from my bookmarklet I just add a.bookmarklet.erb to my views folder. Along with this I make heavy use of partials and have very little duplication between my views.