Getting Cursive's Structural Editing to my Fingers

Time to time, I question the habits I use in my development workflow. For a while, Cursive’s structural editing inspired me. It seemed to be worth getting it into into my muscle memory.

The Context

With VIM, I started to look at editing as programming. I often use macros, and like to think about ways to reach my editing goals the quickest and most elegant way. VIM helps me express my goals in a powerful language.

RubyMine’s refactoring tools helped me to work faster when I want to change my current design into another pattern. It’s more natural and easier to do when the editor understands patterns.

When the editor knows the language I’m thinking in, I don’t need to translate and it certainly saves me a few brain cycles in my workflow.

Structural editing in Cursive is yet another way to express text manipulation tasks for Clojure expressions. As Clojure is a Lisp-dialect, the code itself is a data structure expressed in s-expressions. Editing becomes data manipulation.

I had a bit of problem with shortcut conflicts between IntelliJ, Cursive/structural editing, Chrome, and OSX. I had also listed the changes I made in order to resolve those conflicts.

First, I needed to battle two curious-sounding operations slurp and barf.

Slurp and Barf

Simply told, slurp is like eating up an expression before or after the current list expression (based on the cursor position). Barfing is the inverse operation of slurping. It spits the first or the last expression out.

The default Cursive shortcuts seemed unintuitive at first, but, with a bit of imagination, they make sense.

Backwards Forward
BARF ⌃⌘K ⇧⌘J

Both barf and slurp is about moving the bracket. Control keys ⌃⌘ move the left, ⇧⌘ move the right bracket, K moves right, J moves left. So, this makes it simple to translate that ⇧⌘K moves the right bracket to the right, so it “slurps” the expression behind the bracket.

⇧⌘K was in conflict with the default setting for keyboard layout switching shortcut ⌘K on OSX. I changed that to ⌥⌘;.

Brace manipulations

Wrapping expression with braces works on the expression under the cursor or on selections.

Wrapping Closing
parentheses () ⇧⌘( ⇧⌘)
curly braces {} ⇧⌘{ ⇧⌘}
brackets [] ⇧⌘] ⇧⌘]

Shortcuts ⇧⌘{ and ⇧⌘}, although natural choices, are in conflict with tab navigation shortcuts used also in browsers. I chose to change the tab navigation shortcuts to ⌃J and ⌃K.

Refactoring to threading

Threading macros (-> and ->>) makes nested function calls simpler to read. Cursive’s structural editing supports this type of refactoring.

Turning nested function calls to threading works inside out. It’s probably the best to explain by example. Caret () shows the cursor position, makes a step by pressing ⌥⌘,.

  1. (d (c (b ‸a xb) xc) xd)
  2. (d (c ‸(-> a (b xb)) xc) xd)
  3. (d ‸(-> a (b xb) (c xc)) xd)
  4. ‸(-> a (b xb) (c xc) (d xd))

Mutating back to nested function calls is by ⌥⌘.. Every step keeps the braces balanced and evaluates the same expression.


My goal was to start using structural editing with Cursive. During writing this post, I learnt a lot about it, and also got into a bit of a habit of using it in my workflow. Certainly, there is more to it, but I hope it would help to give some ideas on how to start.

There are also structural editing tools for other IDEs. This thoughtbot post discusses VIM structural editing.

Heimdallr with Active Model Serializers

I have introduced heimdallr in an earlier post. It is an excellent tool for securing models. heimdallr can create proxies for collections and records, it is possible to define scopes for fetching and deletion, and which messages are permitted to be forwarded to the proxied record. I use active_model_serializers for serialization. It provides an elegant way to define serialization rules for the models.

active_model_serializers does not work with the collections and records secured by a proxy out of the box. It would be good to know what should happen when a not permitted attribute is accessed on the model. I thought about two options:

  1. the serializer could raise a permission error or
  2. it serializes a value interpreted as not readable.

I chose the second approach. However, as json does not know about symbols as ruby does, serializing unaccessible attributes as nil seems to a proper option. The consumers of the produced json need to agree on the interpretation of a null value in the received json as a not accessible attribute.

Luckily the described strategy for serializing secured record is very simple. Heimdallr defines method implicit which returns a proxy with a strategy returning nil for unaccessible attributes.

I conclude this post with the short code doing the trick described above:

require 'heimdallr'
require 'active_model_serializers'

module Heimdallr
  class Proxy::Record
    delegate :active_model_serializer, to: :@record

    def read_attribute_for_serialization(name)
      self.implicit.send name


  class Proxy::Collection
    include ActiveModel::ArraySerializerSupport

Backbone forms: How to get ids for objects created on the client side?

I am building an application which is built with Backbone.js. It contains several forms, which make it possible to create sub-items in collections. I run into the issue of getting the id for the recently created items. Let me explain the scenario:

  1. a new model instance is created with and an empty id
  2. the form gets saved triggering a POST or PUT request
  3. the server receives and saves the new and updated items
  4. the new items get the ids filled out
  5. all items are sent back with updated server-side ids

The issue is with mapping the new ids to the instances which are on the client side without an id.

Backbone.js generates a unique client-side cid for every object. The idea was to serialize the cid and send it back from the server with the server side id. As server I use rails. I added new virtual attribute cid to the model and serialized it. For the client models serializing (toJSON) and parsing needed to be updated. Method toJSON was the easy part:

toJSON: function() {
  return _.extend(toJSON.__super__.constructor.apply(this, arguments),
      { cid: this.cid })

Bit trickier is handling of the response coming from the server. It’s necessary to identify the existing item using the cid and update it with the new server side id. After exploring several possible ways, how to do it wrong, I was advised to override the parse method.

parse: function (resp) {
  return, function (attrs) {
    var cid = attrs.cid;
    delete attrs.cid;
    var existing = this.get(cid);
    return existing ? existing.set(attrs).attributes : attrs;
  }, this);

That simple definition of the parse method showed me the elegance of backbone. Searching for a simple solution proved to be worthwhile.

Restricting Models with Heimdallr

I found myself several times implementing the logic for restrictions in controllers. Although that might be fine, when the things get more complex, this practice can become hard to maintain. As modeling restrictions belongs to the core logic of the application, perhaps they should be placed there..

That’s what heimdallr is supposed to resolve. This gem provides model level security by wrapping the model classes and instances by a proxy. The access rights are declared in the model:

class Card < ActiveRecord::Base
  include Heimdallr::Model

  belongs_to :person
  attr_accessible :suit, :rank, :backside

  restrict do |person, card|
    if person.arbiter?
      # the arbiter can do anything
      scope :fetch, -> {}
    elsif person.playing?
      # if the user is playing, only the card at hand is visible
      scope :fetch, -> do
        where(['person_id = ?', person])

The restrict block can take more parameters, based on these we can decide how to restrict the model. The last parameter (card in the example) is an instance of the model, if it is nil the model class was passed to the restrict block. The restriction can be thus called on either the model class or on a concrete instance: Card.restrict(person) vs card.restrict(person).

Heimdallr maintains a scope for fetching and deletion. Scope restriction are obviously useful when restricting the model class. Calling all on the proxied model returns only the cards visible by the person. Wondering how to simply ask whether a card instance is visible by the person? card.restrict(person).visible? does just that. For testing destroy-ability of a record there is destroyable?.

I covered briefly scope restriction using heimdallr in this post. However, there is yet more how heimdallr can help. Finer restrictions, such as attribute visibility and updatability are often crucial as well. But let’s leave this for later.

Non-Modal Inline Dialogs: Ask Questions in Awesome Ways

Asking questions, confirmations from the users is a pretty usual part of any user interface. Still often I find tackling this simple task solved in unsatisfying way. The simplest solution is the confirm('ask your question..'); dialog. However, this often ruins the otherwise possibly clean design. Confirm dialogs are modal and therefore users can not proceed further actions without answering the questions. But what if you do not need immediate answers? Often it is enough leaving the dialog questions opened. In such situation try using “inline dialogs”.

simple modal dialog with a yes-no question

Let’s build a simple scenario. We have three simple events which the user can trigger: calling a firemen, calling police or ambulance. Obviously triggering these events could be useful to handle with a simple question before they are really triggered. If this security question is answered positively, the event is triggered, otherwise the original Call the … link is rendered. The dialog blocks are divided into a trigger and question part.

    <DIV CLASS='dialog_block' DATA-MESSAGE='Calling the firemen!'>
      <A HREF="#" CLASS="dialog_trigger">Call the Firemen!</A>
      <DIV CLASS="dialog_question">
        <A HREF="#" CLASS="answer_yes">Yes</A>
        <A HREF="#" CLASS="answer_no">No</A>
    <!-- do something similar for the two other calls -->

For handling the dialog actions I use jQuery now. We need only three simple callbacks for handlers: activation of the question trigger, handler for the yes and the no answer.

var turnOffDialogQuestion = function(el) {
  $dialog_block = getDialogBlock(el);
    function() {
var getDialogBlock = function(el) {
  return $(el).parents('.dialog_block');
$(document).ready(function() {
  $('.dialog_trigger').click(function(ev) {
    $dialog_block = getDialogBlock(this);
      function() {
    return false;
  $('.dialog_question .answer_yes')
  .click(function(ev) {
    return false;
  $('.dialog_question .answer_no')
  .click(function(ev) {
    return false;