We have been developing gems a lot as part of giving more structure to Rails applications: the idea and some techniques. Doing this often sees a Rails application and one or more gems being developed at the same time. This unfortunately breaks Rails autoloading. This article will show you how to get it back…
Community
HQ
Explore Blog posts about everything we are up to, Tech Talk videos covering a huge range of timely topics and Event listings to keep you current on happenings at the Labs.
= != send(:=)
Interestings
Sending Assignment
Ruby enforces that any assignment returns the RHS. Or at least it does when you call it normally.
class Foo
def bar=(x)
42
end
end
Foo.new.bar = "sup"
"sup"
Foo.new.send(:bar=, "sup")
42
(looks like its fixed in newer versions of 2.0)
Design for Hackers!
Interestings
Design for Hackers free email course
Summer of Design is 12-week series of emails. The learning material is designed to help developers, hackers, and makers of any kind really understand the “whys” of design. Sign up for free until June 3.
WWDC Panel at Pivotal Labs
Join Pivotal Labs, AppOrchard and Apress for a night of WWDC post-session beer + expert commentary on Wednesday, June 12th at Pivotal Labs. Apress iOS expert authors Ash Furrow, James Dovey and Kevin Y. Kim will be joined by Randall Thomas of Thunderbolt Labs and Davis W. Frank of Pivotal Labs in reflecting on the sessions, announcements, and updates from the conference. They will discuss what foreseeable new development hurdles or long-awaited resolutions will come from changes to the OS, the form factors or the products. Come prepared for a lively and fun evening!
Register at: http://applesandoranges.eventbrite.com/
Pair Comics
There are particular tropes that come up again and again when pairing. I’ve decided to canonize a few as comics. Enjoy!
Better Project Integration with RubyMine’s Tool Windows
RubyMine’s tool windows integrate common development tasks such as searching, debugging, and version control, into the IDE. This eliminates context switching to external tools, providing a more fluid development experience. In this post, we’ll look at some common commands for managing tool windows in RubyMine on OS X.
Opening and Closing Tool Windows
Each tool window is given a number. They can be opened or closed with command + <number>, e.g., by default, the Project tool window is given command + 1.

Opened tool windows are located on the bottom and sides of the IDE.
Navigating Between Tool Windows
To navigate between opened tool windows, first open the Switcher with control + tab. Then continue holding down control and press the number of a specific tool window.

While holding down control, use option to move between the Switcher’s two columns.
Navigating Between Tool Windows and the Editor
Press esc in a tool window to move focus to the editor. Use F12 to move focus back to the tool window.
Closing Tool Windows
Close tool windows with command + w. Use shift + esc in a tool window to close it and move focus to the editor.
Close all opened tool windows and move focus to the editor with command + shift + F12. Press it again to re-open the tool windows.
Don’t Sell Your IDE Short
Many developers insist of performing certain tasks outside their IDE. Perhaps they fear losing skills they’ve heavily invested in. For certain exceptional situations, e.g., debugging production, it’s important to know how to do these tasks without an IDE. But when it comes to day-to-day development, embrace your IDE and experiment with a new way of doing old things.
Cucumber: When to Use It, When to Lose It
I had really poor experiences with Cucumber. The annoyance with Cucumber comes nearly all from a case of indirection. If devs are writing the Cucumber tests and then writing all the regular expressions to implement the steps, then you often wonder why the heck you’re not just writing tests in Ruby. SO WHY DON’T WE JUST WRITE RUBY AND SKIP THE INDIRECTION?!?!?!
On a recent project however, my anchor spent the first 3-4 weeks with a lot of hands-on time working with the PM to get the PM to write stories in Tracker with multiple scenarios in the “Given… When… Then…” syntax. We then paste it directly in to a .feature file and start defining the steps. We don’t try to reuse steps very much. This means steps.rb becomes a type of dumping ground and you just have to let that go. WHAT YOU HAVE TO DO is not put much in the steps.rb and build up a “language” that lives in your helper files which are well maintained and clean. This is the key. Some rules of thumb: steps should be short, one line is best. No Capybara in your steps, so don’t say “visit new_user_form” or “page.should have_content(…)” in your steps, put that in a helper method or custom RSpec matcher that is like “open_user_form” or “widget.should have_success_message” respectively. This way, when you look at the step because you are walking through the layers of indirection, it’s really clear what’s going on, and really straight forward to update when your UI changes – because it will.
You could (and should) do a lot of the same things in plain-Jane Capybara specs, it’s just good practice to be pulling up this domain specific language. The value of Cucumber comes in when a PM is writing the specs. It’s time consuming for that PM though. In an hour long story writing session, we get through writing about three stories. It works well for our team of 4 engineers and 1 designer. I don’t know that it would scale well to a team of 8 that needs more stories each week. We also take our Cucumber features and publish human readable documentation via Relish, so future devs or PMs could have some expectation about our intentions.
If only coders are reading and writing the specs, forget Cucumber. If non-coders are actually participating, then Cucumber starts to make sense. I find that we basically end up paying the specification cost up front. I know it works because in our team of 4, we rarely disagree on estimates (we always throw the same number). The payoff is that on this project we don’t have to turn to our PM for clarification nearly as much as I’ve had to on other projects.
The caveat though is that payment of cost up front. If you’re writing ten stories a week and throwing eight away, you’re wasting a lot of time and energy writing stories. Stories are fairly stable on projects where we’re doing re-writes and thus the feature set is known, or where the feature set is VERY well defined (as may be the case when cloning functionality inan existing product). In most other projects, the backlog gets shuffled around a good bit as things get released, users give feedback, and company priorities shift. In this later case, you want to put in some minimal effort upfront on story writing and pay the rest of the cost during IPMs and once the story is picked up by a pair. Cucumber has its place, it’s just not every place.
Why Pivotal
It is a time-honored tradition for Pivots to blog about their first few months at Pivotal. A typical day at Pivotal is strong work. It’s different from any previous job. It’s exhausting. After six weeks or so, however, the Pivots find their rhythm. I’m not going to write any more about that. I’ll include some links, below, so you can read them for yourself. I’m here to write about the two-years-later; When most developers are itching to move on to the next big thing. I’m still happily learning new stuff every day.
Making Better Developers, One at A Time
But first… some true stories
I was a dot.com’er in the 90’s. I was on a planned sabbatical when the dot.bomb hit and lots of people got laid off. I became a SCUBA instructor in Hawai’i; I couldn’t get any tech work and I just happened to be in Hawai’i at the time. It is the hardest job I’ve ever had. Nothing else comes close. Yes, I got to dive in near-tropical waters (Hawai’i isn’t technically in the tropics, did you know that?), but I also had to haul 2,000 pounds of gear up and down slippery steps, comfort the deathly sea-sick on the calmest of days, wash dive gear reeking of urine, and smile, even when the rain is pouring, the water is pea-soup, and the tips are scarce. All for an AGI of $18K in my best year. A walk in the park it ain’t, and yet there were other rewards.
I have certified hundreds of divers. Industry-wide, only a very small percentage become lifetime divers. Most finish the basic course and never dive again. If I dwelt on the number of divers who didn’t continue, I would be quite depressed, but I don’t. I look back on all the ones who are still in it and I smile. I take deep satisfaction in all the lives I changed during those years. That’s why I did it. No paycheck compared with seeing someone’s eyes get this big at their first sight of a sea turtle, up close. If I could have survived without an income, I would have done it anyway just for the joy of it. I told my friends I was making better divers, who in turn became better human beings.
At Pivotal, I’m making better developers, one pairing session at a time.
When Paul Vixie put MSN on the RTBL
Paul Vixie and I crossed paths a few times in the late 90’s, when I was a sysadm (predating devops). Paul Vixie and Dave Rand created MAPS to combat spammers. Among other things, a lot of mail servers, open source and otherwise, had open-relay turned on by default, making trouble all over; any mail client, anywhere, could connect to port 25 and the mail server would blindly forward it on to its destination, even outside of the domain.
In early 1998, MAPS received complaints about msn.com. Following protocol and after a lot of calls from MAPS and silence from MSN, msn.com was placed on the RTBL. Suddenly, thousands of customers were faced with mysterious error messages about SPAM and their e-mail was not delivered. You can search for the event; you’ll see a lot vitriol against Paul and MAPS over the incident. I remember Paul recounting how, in a tense meeting in Redmond, when the MSN management (finally) admitted that yes, there was a problem but they had a plan (already in place) to fix the problem, Paul opened up his laptop and took msn.com of the RTBL right then and there. The MSN management was shocked. For Paul, it was obvious.
“I don’t hate spam, I just want to make better sysadmins.”
Pivotal Lab’s Mission
“To transform the way the world builds software”
Heady stuff. But how do we do it? We engage with clients, build product and show them, by doing, that our methods really are better. We don’t lecture, we don’t offer certifications, there’s no Pivotal University. We “do.” Does every client leave transformed? No, not really, but like my divers, all of them have been affected, and some are transformed. They go on to do great things after the engagement is over. (And, no matter what else, every one has built something valuable along the way.) Like Paul, we’re not haters. We want to make better developers.
After 30 years, I’ve worked at more than a few jobs; I’ve been a dishwasher, a sysadmin, and a SCUBA instructor, my .emacs file dates back to 1982. Even so, working at Pivotal is still the best job I’ve ever had.
Playing with Ember.js and Devise
I have been playing with Ember in and out since the beginning of 2012, you may have seen my two (obsolete?) libraries ember-facebook and ember-formbuilder. I wrote them out of real needs I had on projects back then.
I was away from ember since version 0.9.8 and ember-data I don’t even remember if it had a version number yet, and I started playing around with it again this last few weeks.
Right now there are not a lot decent resources of getting started with ember and unfortunately some of them are outdated. I am sure that this will get better and better now that the framework is stabilizing.
Anyway, I am working in a little project with a friend and we decided to use ember on it. First thing we implemented was authentication. This is a very simple problem with several solutions. We want to use devise. A very simple one is to rely on the devise’s engine and just make it a separate part of the app, after that you render the user’s session JSON on a metatag and parse it in ember. There is a very nice tutorial on how to do that by Alexander Zaytsev here.
Alternatively you can implement all the interface yourself and have a truly single page application, and it is not that hard. First thing you have to do is turn devise into an API by creating a few controllers. I am just going to show sign-up and login here.
Turning Devise into and API
For sign up let’s create our own users controller to handle registrations:
class UsersController < ApplicationController
def create
user = User.new(params[:user])
if user.save
render json: user, status: :created
else
respond_with user
end
end
endIt’s very simple, an API endpoint to create users using the devise’s user model and respond with the JSON for that user (you may or may not be using active_model_serializers here, but you should be).
Similarly we create a sessions controller to handle, well, sessions:
class SessionsController < ApplicationController
def create
user = User.find_for_database_authentication(email: params[:session][:email])
if user && user.valid_password?(params[:session][:password])
sign_in user
render json: {
session: { id: user.id, email: user.email }
}, status: :created
else
render json: {
errors: {
email: "invalid email or password"
}
}, status: :unprocessable_entity
end
end
def destroy
sign_out :user
render json: {}, status: :accepted
end
endThis one is longer, but it is also very simple: we find the user, we validate whether the password is correct and we then respond with either the basic user data and a successful status or an error message to be shown by ember with an errors status.
We are also adding the destroy action for loggout.
Don’t forget that you need to add theses to your routes.rb:
resources :users, only: [:create]
resources :sessions, only: [:create, :destroy]Models
We are going to need two Ember models for this, one for our registration and another for the sessions, models in ember-data are extremely simple and there is not a whole lot to say about them.
App.User = DS.Model.extend({
email: DS.attr('string'),
password: DS.attr('string'),
passwordConfirmation: DS.attr('string')
});
App.Session = DS.Model.extend({
email: DS.attr('string'),
password: DS.attr('string')
});That is already enough for us to play around in the console and create users/sessions:
var user = App.User.createRecord({email: 'foo@bar.baz', password: 'password', password_confirmation: 'password'});
user.save();
var session = App.Session.createRecord({email: 'foo@bar.baz', password: 'password'});
session.save();Routes
Let’s define our routes:
App.Router.map(function() {
this.resource('users', function() {
this.route('new');
});
this.resource('sessions', function() {
this.route('new');
this.route('destroy');
});
});The first two routes we have to add are simple and are just setting the content properties of their controllers. The destroy route is slightly more complicated:
App.UsersNewRoute = Ember.Route.extend({
model: function() {
return App.User.createRecord();
},
setupController: function(controller, model) {
controller.set('content', model);
}
});
App.SessionsNewRoute = Ember.Route.extend({
model: function() {
return App.Session.createRecord();
},
setupController: function(controller, model) {
controller.set('content', model);
}
});
App.SessionsDestroyRoute = Ember.Route.extend({
enter: function() {
var controller = this.controllerFor('currentUser');
controller.set('content', undefined);
App.Session.find('current').then(function(session) {
session.deleteRecord();
controller.store.commit();
});
this.transitionTo('index');
}
});This destroy route does not have a controller or view (at least not an explicit one), it basically unsets the content of the currentUser controller (check next section) then issue a delete request on the sessions controller of our API and redirect the user back to the root. Note that we are “finding” the session using the id of “current”, ember-data does not support singletons explicitly, so we have to work around that fact by doing that. You can read more about this here.
Current User
This part is based on the post I mentioned earlier by Alexander Zaytsev. It’s an object controller that will hold the existence (or not) of the current user session.
App.CurrentUserController = Ember.ObjectController.extend({
isSignedIn: function() {
return this.get('content') && this.get('content').get('isLoaded');
}.property('content.isLoaded')
});We’ll also need this initializer to populate it once the app is loaded.
Ember.Application.initializer({
name: 'currentUser',
initialize: function(container) {
var store = container.lookup('store:main');
var user = App.User.find('current');
container.lookup('controller:currentUser').set('content', user);
container.typeInjection('controller', 'currentUser', 'controller:currentUser');
}
});Here we’re asking or API for the current user with the same singleton strategy App.User.find('current'), the app is supposed to return either a successful message with the user JSON or an error. We now need a show endpoint in our users controller, as simple as respond_with current_user, don’t forget to add the show route in your resource on routes.rb.
Templates
We need two things here, we need a sign up form and a login form. Another thing we may want is navigation links. Let’s start with the forms. There is no point in logging-in if you don’t have an account right? So let us sign up!
<h1>Create an Account</h1>
<form class="form-horizontal user-form">
<fieldset>
<div class="control-group" {{bindAttr class="errors.email:error"}}>
{{view Ember.TextField valueBinding='email' name='email' placeholder='Email'}}
<span class="help-inline">
{{errors.email}}
</span>
</div>
<div class="control-group" {{bindAttr class="errors.password:error"}}>
{{view Ember.TextField type="password" valueBinding='password' placeholder='Password'}}
<span class="help-inline">
{{errors.password}}
</span>
</div>
<div class="control-group" {{bindAttr class="errors.passwordConfirmation:error"}}>
{{view Ember.TextField type="password" valueBinding='passwordConfirmation' placeholder='Password Confirmation'}}
<span class="help-inline">
{{errors.passwordConfirmation}}
</span>
</div>
<a href='#' {{action cancel}} class='btn'>Cancel</a>
<button type="submit" {{action save}} class='btn btn-large btn-primary'>Sign Up</button>
</fieldset>
</form>
Assuming you’re on rails and using the standard ember gems you should put this file in app/assets/javascripts/templates/users/new.hbs, ember will automatically pick it up if you follow it’s defaults.
I am using a bootstrap form structure here to show the inputs and error messages. Ember-data will automatically populate the errors property for you if you’re API is returning the right thing, which it is.
And our Login form:
<h1>Login</h1>
<form class="form-horizontal user-form">
<fieldset>
<div class="control-group" {{bindAttr class="errors.email:error"}}>
{{view Ember.TextField valueBinding='email' name='email' placeholder='Email'}}
<span class="help-inline">
{{errors.email}}
</span>
</div>
<div class="control-group" {{bindAttr class="errors.password:error"}}>
{{view Ember.TextField type="password" valueBinding='password' placeholder='Password'}}
</div>
<a href='#' {{action cancel}} class='btn'>Cancel</a>
<button type="submit" {{action save}} class='btn btn-large btn-primary'>Login</button>
</fieldset>
</form>This files goes into app/assets/javascripts/templates/sessions/new.hbs.
Very similar to the sign up form, in this case we’re only showing errors on the email field because we’re not specifying whether the email or password was wrong, sometimes you may want to do that, this is not our case here.
There you have it, a very simple sign up and login for that will just work. Right? No, we still have to define our actions, but we’re getting there. Note that we defined in both forms {{action save}} in our submit buttons, now we need our controllers to handle that.
Oh, and you may also want to add these navigation links somewhere:
{{#if currentUser.isSignedIn}}
Logged in as {{currentUser.email}}
{{#linkTo 'sessions.destroy'}}Logout{{/linkTo}}
{{else}}
{{#linkTo 'users.new'}}Sign Up{{/linkTo}} |
{{#linkTo 'sessions.new'}}Login{{/linkTo}}
{{/if}}Controllers
Currently we have defined one controller that is the currentUser controller to control the active session, we now need to define controllers to react on actions on our forms, once again we’ll start with the signup form:
App.UsersNewController = Ember.ObjectController.extend({
save: function() {
var self = this;
this.content.save().then(function() {
self.transitionToRoute('index');
});
},
cancel: function() {
this.content.deleteRecord();
this.transitionToRoute('index');
}
});When the user hits ‘save’ we tell the model to save itself this.content.save() and then we redirect the user to the root when we’re done. Everything else is being handled by ember and ember-data here behind the scenes, validation errors will automatically update the bindings in the template and will NOT call the ‘then’ callback.
When the user hits ‘cancel’ we just clean up the model this.content.deleteRecord() and redirect back to the root.
The sessions controller is a bit more complicated, let’s take a look:
App.SessionsNewController = Ember.ObjectController.extend({
needs: ['currentUser'],
save: function() {
var self = this;
this.content.save().then(function() {
var userJSON = self.content.toJSON();
userJSON.id = 'current';
var object = self.store.load(App.User, userJSON);
var user = App.User.find('current');
self.get('controllers.currentUser').set('content', user);
self.transitionToRoute('index');
});
},
cancel: function() {
this.content.deleteRecord();
this.transitionToRoute('index');
}
});The ‘cancel’ action here is exactly the same as before, so let’s talk about saving. The first step is the same, we ask ember-data to ‘save’ our model this.content.save() and we hook into the ‘then’ callback. Since our create session endpoint is return a user’s JSON we’re gonna use it to populate the currentUser controller. At this point self.content.toJSON() will have the user’s email, but it may have more information as you application needs grow. We have to manually set the ‘id’ property on that JSON object since ember-data will not serialize it. We set it to ‘current’ to refer to our singleton currentUser.
And then we finally load that into a User object using the ember-data store. We then set the content of our currentUser controller to be that loaded user: self.get('controllers.currentUser').set('content', user).
And there we have it, if everything is wired correctly we should have a working signup/login/logout app. I hope it was as helpful for you as it was for me.
References
- Alexander Zaytsev – Using Rails & Devise with Ember.js
- Brian Cardarella – Building an Ember app with RailsAPI
- Jesse Wolgamott – API JSON authentication with Devise
Caveats
1. I had to add this line to my devise.rb file inorder to be able to get rid of the devise_for :users on the routes.rb file. That’s because devise won’t provide you with the dynamic helpers like current_user or user_signed_in? if you don’t call add_mapping, and devise_for calls that method underneath the hood.
config.add_mapping :users, {}2. This strategy relies on cookies and sessions, if you’re going with this instead of using a auth token you should make sure your app is secure by having protect_from_forgery on. Then you will need to hack into ember-data’s ajax adapter to send the csrf-token on every request. You can achieve that with something like this:
$(function() {
var token = $('meta[name="csrf-token"]').attr('content');
$.ajaxPrefilter(function(options, originalOptions, xhr) {
xhr.setRequestHeader('X-CSRF-Token', token);
});
});Everything I know about Clojure after one week
This week I decided to clear out the cobwebs of my Ruby-trained brain and try a completely different language. Ruby and Rails have been my staples for over seven years, and I’m starting to tire of my patterns of thinking, and of the common problems found in large Rails applications. Specifically, I’m pretty bored of running into slow test suites and difficult-to-maintain apps. I suspect the primary cause of these problems is the entanglement of business logic with database and other stateful resource code. I get the feeling that it can’t be just coincidence that so many teams of competent developers fall into the same old traps.
I’d heard a bit about Clojure, so decided to explore the ecosystem and community. I’m attracted to the idea of learning a functional language, avoiding mutable state and re-evaluating the object oriented programming paradigm. Functional programmers are often accused of being “idealistic”, “academic” or a variety of other thinly-veiled primitive insults. If nothing else, I could learn to sympathise with these crackpot underdogs who claim to have the cure for most of the technical pain I suffer in my chosen occupation.
Hopefully this assortment of links and lessons learned will encourage you to try out the language, or inspire you to try something else that’s refreshingly new.
Clojure is easy to get started with
There are various tutorials online. However, they can be a little out of date. The quickest route to Clojure hacking is via leiningen, a sort of rake-meets-bundler utility. Assuming you’re on a Mac, have homebrew installed, a recent JDK and the usual code compilation dependencies:
brew install leiningen
lein repl
That’ll pull in Clojure for you. Once you’ve had a play in the REPL, use leiningen to generate an app:
lein new my-test-projectThe project.clj that the above command generates is the equivalent of a gemspec, and declares the dependencies of your app. Leiningen helpfully fetches dependencies lazily when you start a repl, server or run tests. No bundle install step!
Homebrew can also install Clojure for you, but this version will be independent of leiningen apps. When you install it, you’ll be recommended to use a REPL wrapper for rlwrap. I’ve found that the one from the wikibooks site works better (i.e. at all).
Rich Hickey is an entertaining figurehead
Rich Hickey, creator of Clojure and designer of Datomic, the FP-friendly database system everyone’s talking about, has some inspiring talks from the end of last year about Clojure and Datomic, and notably why everybody is doing programming wrong. There are some pretty strong views in the talks, but they’re a refreshing take on the sociological patterns in our industry, and how project pathologies can be treated.
There’s an active community
Many clojure developers are ex- or current-Rubyists. For example, Jay Fields maintains the expectations testing library (more on this below).
Clojure has artsy cred, too: there are several videos on the web showing Clojure being used for live music.
Syntax change requires healthy brain re-wiring and thought simplification
After spending so much time wrapping my head around object-oriented constructs and trying to work out how best to structure OO programs, it’s a refreshing change to work with a functional language. Not having a CS degree, I’d previously tinkered with Scheme following a workbook. I wasn’t put off by parentheses, but did have some fears that I’d be transported back to the bad old days of the top-level PHP namespace. I soon realised, however, that my beef with PHP was mainly the aforementioned comingling of state and logic, as well as the inconsistencies of method signatures and names.
Clojure philosophy is all about consistency and reuse. I’ve trained myself to believe that reuse is all about identifying concepts, naming them and adding an abstraction, often a named value object. I’m pretty attached to my explicitly named classes of values, like SubscriptionEvent or PersonName. This is largely in reaction to the recognisable OO smells like Primitive Obsession. The problems inherent in such smells generally melt away in the FP world, since you’re encouraged to use the built-in types to provide equality and the like, and to use the common functions like map, reduce and so forth to achieve what you would do in OO with a value object’s methods.
Web development is potentially full-stack
This is worth knowing if you don’t already: Clojure already compiles to JavaScript in the browser, as well as to Java on the server. So we potentially could be doing single-language full-stack development like node.js but without the oft-cited pitfalls of JavaScript. An excellent resource for newcomers to Clojure is this translation between JS and Clojure.
I’ve begun a project for playing around with the Compojure web routing library. Compojure forms the basis of many Clojure web apps, and I’m using that repository as a place to stick my learnings. I’m test-driving each new feature, so that it might serve as a reference for other newcomers on how to do TDD for Clojure web apps.
TDD is easy, fast and totally not banned.
Watching the Hickey talks, you might come away with the impression that the Clojure community is anti-TDD. However, there are some excellent developments going on in this area, such as the aforementioned Jay Fields’ expectations library, which provides an achingly simple way to express intent in tests. See my first attempts at testing a web app for an example of this. Structural whitespace optional.
Monads still a mystery
One week just wasn’t enough. See if you can figure it out and send me a postcard with a succinct summary.
Until next time!




