Skip to content

Instantly share code, notes, and snippets.

@dnagir
Created November 23, 2012 02:27
Show Gist options
  • Select an option

  • Save dnagir/4133761 to your computer and use it in GitHub Desktop.

Select an option

Save dnagir/4133761 to your computer and use it in GitHub Desktop.
Unobtrusive and testable AJAX in Rails 3

The problem

Initially asked at RORO but I will elaborate with an example.

What we need to do is the following:

  • we list a set of items (let's say posts) and want to show a drop-down menu next to each one (quick example)
  • when the drop-down arrow is clicked the menu is loaded from the server.

Now, the menu will content a few normal links, but will also have one interesting: Hide (or Unhide depending on the status of the item).

The Hide functionality will have to do the following:

  1. When clicked the menu is hidden.
  2. The server is notified about the action (POST to hide).
  3. The item is removed with an animation.
  4. The alert is is added with the link to the hidden items (like so).

Start with the HTML

So we need to have the following "widgets":

  1. Remote dropdown.
  2. Posting to server when link is clicked.
  3. Hide the dropdown.
  4. Replace HTML on the page with a server response.

Step 1. The remote dropdown

HTML

We can use Twitter Bootsrtap's Popover for this to have the ability to render any content.

Desired HTML:

- # The buttons section:

.btn-toolbar
  .btn-group
    %a.btn.btn-info{href: post_path(post)}
      %i.icon-list.icon-white
      = t '.read'

   -# This anchor is what we want
    %a.btn{href: controls_post_path(post), 'data-shows-popover' => 'remote'}
      %i.icon-cog
      %span.caret

And the related view spec

require 'spec_helper'

describe "posts/_controls" do
  subject { render partial: "posts/controls",  locals: {post: post} }
  let(:post) { stub_model(Post) }

  it { should have_selector("a[href='#{controls_post_path(post)}']") }
  it { should have_selector "a", href: controls_post_path(post), 'data-shows-popover' => 'remote' }
end

# routing assumed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment