I was poking around the ThoughtBot blog a couple of days ago and ran across a post titled Refactoring Ruby Iteration Patterns to the Database. At a high level, the post was summarizing how you can take an ActiveRecord aggregation (a sum in this case) and run it in directly in your RDMS with SQL. Not really rocket science, but it was a keen reminder of how ORMs often mask over much of the power of “regular” SQL. This isn’t a specific criticism of ActiveRecord, it’s an issue with every ORM from Doctrine to Hybernate.

We’ve actually been writing some straight SQL lately, mostly for analytics work, so I had the team shoot over their favorite “maybe hidden” SQL feature. Since life is better with examples, the sample use cases and queries are written against a schema describing the “items” found on a “receipt” which are optionally related to a “category”. The SQL to create the schema is:

Note: SQLFiddle is unfortunately down right now or I’d add this as a fiddle. Anyway, if you have the schema setup feel free to run the queries as you go down the list.

Order rows by fixed ordering of a column

At some point, you might find yourself needing to sort a list of rows by a column in an arbitrarily enforced order. For example, say on our item table, you needed to sort the rows by the “quadrant” column such that WE was first, followed by AX, and finally BT.

Turns out, it’s possible to specify an arbitrary ordering using the ORDER BY FIELD statement:

Check that a LEFT JOIN relation exists

If you’re only running JOINs on columns with foreign key relations this isn’t an issue, but what happens if you need to run a JOIN where a FK doesn’t necessarily exist? In our example, lets say you wanted to select only the items which had a corresponding row in the “receipt” table.

The most straightforward way to accomplish this is generally to check that the JOIN’ed column on the related table isn’t NULL:

Assign an aggregate value to a variable and re-use

One of the SQL features that’s usually glossed over or ignored in web development is the ability to create variables and then reuse them in subsequent statements. With this schema, an example would be calculating the “% of total spend” for the individual items – most people would run one query to generate the total and then a separate query to calculate the % of spend. For something trivial like this it doesn’t matter but if you were involving complex WHERE predicates it could be a nice performance boost.

The syntax for variables is relatively easy and it’s actually a powerful concept:

Add synthetic “pseudo” columns using variables

This one is a Matt Daum favorite and pretty handy. Looking at the example, say that you wanted to assign a “sequence” value to each item depending on their rank order based on “total” within their “category_id”. In plain English, for each “category_id” you want to assign the most expensive item a “1″, the second most a “2″, and so on.

This seems straightforward, but try and construct a result set using only a GROUP BY or some combination of sub queries, I’ll wait. Turns out, the easiest way to accomplish this is to use variables to construct a “pseudo” column that increments and resets when the category changes.

Select only GROUP’ed rows that fulfill a second clause

Sorry for the terrible description, an example will make it clearer. Given our schema, lets say you wanted to select *only* the most expensive items per category, how could you set about doing it? The obvious approach would be using some combination of GROUP BY and MAX but unfortunately because of the semantics of GROUP BY that wont work as expected.

A better approach, is to leverage an INNER JOIN along with MAX() to only select the rows that match the max total per category:

The caveat here is that you’re really selecting the highest total, so if two rows have the same total you’re not guaranteed which one you’ll end up with. This approach also scales out, in the sense that you can add additional INNER JOINs to limit the resultset in situations where you’re getting tripped up by GROUP BYs and ORDER BYs.

Anyway, as always, we’d love to hear your favorite tips and tricks in the comments!

Last week, we were using Phonegap Build to build an iOS IPA for a project an ran into an odd issue. When we launched the app on an iPhone 5 running iOS7 black bars appeared at the top and bottom of the screen. On top of that, when launching the app we were observing the same issue with the splash screen.

In typical Phonegap fashion, Googling for people suffering from similar issues brought back dozens of results across several versions each with a different root cause and solution. One of the first promising leads we noticed was this comment in the top of the default Phonegap template:

Unfortunately, that comment seems either be invalid or the issue has since been resolved since removing those meta attributes had no effect.

As it turns out, the issue is that the “config.xml” file created by the default Phonegap “Hello world” project is missing an entry for the iPhone5′s screen size. Oddly enough, there’s actually a splash screen image of the correct height in the demo project but its not referenced in the config file. To resolve this issue, you just need to add this line to your config.xml:

Just make sure that you have a file named “res/screen/ios/screen-iphone-portrait-568h-2x.png” where the rest of your splash screens are and you should be good to go.

We’ve worked with our clients to execute a couple of Phonegap apps lately and in doing so used Backbone and Marionette to structure the apps. For some background, Phonegap, now Apache Cordova, is a project that allows developers to build native iOS, Android, and WP apps using HTML, CSS, and of course Javascript. As a developer, you write some HTML and Javascript, pass it to Phonegap, and Phonegap returns a native app that displays your code inside a WebView without any surrounding chrome. On top of this, Phonegap provides a set of Javascript APIs that allow you to leverage some of the device’s native functions, like the accelerometer or camera.

Writing apps with HTML/JS is great, but it presents some issues particularly that triggering a full page reload for navigation appears “non-native” on mobile. On technique to combat this issue is developing single page Javascript apps. In a single page app, the entire page is never reloaded, instead portions of the DOM are dynamically re-rendered using Javascript. Because of the complexity of managing this process with straight Javascript, several libraries, including Backbone, have been developed to simplify this process. Marionette is a companion library to Backbone which provides a set of features to make managing complex applications easier. So, what were the pros and cons of using Backbone with Marionette to build a Phonegap app?

The Good

Structure: Using a library like Backbone guides you to structuring your code in loosely a MVC design pattern. Coupled with a templating framework, this ends up producing code that’s much easier to follow and maintain. Before Phonegap, I’d already started using Backbone in traditional Symfony2 projects just to get the benefit of better structured code.

It’s familiar: This is a personal preference, but compared to declarative frameworks like AngularJS, Backbone/Marionette apps “look” like regular HTML/JS. Primarily because of the regular HTML templates and use of jQuery, the learning curve for Backbone isn’t very steep. A team member without Backbone experience can quickly grok how things work and make changes quickly.

The Not So Good

“There’s more than one way to do it”: Although flexibility is good, having a generally “well recommended” way usually helps decrease confusion and frustration. With Backbone/Marionette, there doesn’t seem to be much consensus on how to do “standard” things like message passing or even structuring the app as a whole. There’s dozens of StackOverflow answers debating the “best” way to approach things, often with outright conflicting viewpoints. In contrast, Symfony2 and Rails typically have “best practices” for approaching common tasks, even if they’re not appropriate in every circumstance.

Documentation: The documentation for Marionette, and to a lesser degree Backbone, is pretty lacking. The Marionette documentation explains how the individual components work but they didn’t provide much insight to the “big picture”. The docs were also missing some explanation into the “why”, which of course lead to StackOverflow answers and then differing viewpoints. Marionette is also short example apps which Backbone does have. The Backbone documentation is thorough, its just a bit hard to navigate and purposefully introduces the “There’s more than one way to do it” mantra.

Anyway, on the whole using Backbone with Marionette to build a Phonegap app was a positive experience. Unfortunately, our clients’ own the code so we can’t release it. That said, we’ll do our best to build something in-house that we can share.

Earlier this month one of our clients, SoonSpoon, launched a reservation site that caters towards diners looking to score last minute reservations at some of the most intimate and creative restaurants in Boston. The growing list of partner restaurants such as L’Espalier, Menton and Journeyman are able to use the SoonSpoon website to list last minute reservations that surface as a result of cancellations. Soonspoon then disseminates the open reservations to users through an constantly updated listing on their website, text, twitter and email. As soon as the listed reservation is booked by a spontaneous diner the restaurants receive a text informing them that SoonSpoon has them covered and their table filled.

A few months ago SoonSpoon co-founders Travis Lowry and Conor Clary approached us for help finalizing the last pieces of back-end functionality required to get their platform production ready. We added a mobile-friendly dashboard for restaurants to easily list new reservations as well an integration with Twilio’s REST API for sending SMS messages. It was great to see this thing lift off successfully and we wish these guys the best of luck – with close to 500 diners , 14 partner restaurants and plans to expand to other cities it looks like they’re off to a great start!

If you want to read more about these guys their website is www.soonspoon.com and twitter handle is @soonspoonhq.  Here’s some recent press from Boston EaterBoston Business Journal and Boston Magazine.

In the last two weeks, there’s been two frontpage stories coming out of the “sharing economy” space. First up, news broke that Seattle passed new regulation to limit the number of drivers that Uber or Lyft can have on the road at any time, effectively hamstringing both services. Then, over the weekend a story started circulating about an Airbnb stay gone awry involving an orgy, Twitter, and of course the cops. While the stories are wildly different, they both sit at the intersection of the new “sharing economy” and the role of government regulation. Because of this, both stories sparked an intense debate everywhere from The Wall Street Journal to Hacker News. The attitudes and viewpoints of the discourse were interesting and revealing about people’s attitudes towards regulation in the taxi and hospitality space.

The opinion towards the new regulations in Seattle were overwhelmingly negative, ranging from claims of stifling innovation to accusations of outright corruption. Empirically, it seems that most people, even outside of early adopters, have generally positive feelings about Uber and Lyft. It might be because of the horrible experiences people have had in normal cabs or because of the perception of hackney companies as entrenched monopolies but I think it’s primarily due to people’s perception of risk surrounding Uber or Lyft. As a non-user, the perception of how “risky” it is to have Uber drivers operating in your city is probably near zero. Given how small a percentage of total drivers they’ll make up and that “licensed cab drivers” typically already operate in the area, I don’t think many people feel threatened by having additional drivers potentially ferrying people around their city. Because of this, it’s been easier for people to take hold of the “sharing economy” narrative where Lyft or Uber who were empowered to make a living are suddenly shut out by corrupt, entrenched interests.

Contrast this with the reactions from the same people to the Airbnb story, which ranged from disgust that someone would rent out their condo to strangers through feelings that Airbnb should be held liable for the actions of an independent third party. There’s no argument that the Airbnb story is significantly more disturbing, but it isn’t the first time something like this has happened and it certainly won’t be the last. So why such a different, visceral reaction? It’s perceived risk. As a non-user, the perceived risk to having Airbnb operate in your area is undeniably significant. Take a typical condo apartment building where every occupant is either a member of a condo association or a vetted rental tenant. Introducing the possibility of short term, “random occupants” certainly sounds risky and unnerving to anyone living in the building. Anyone considering the situation immediately evaluates worst case scenarios, “what if they’re criminals?” or “drug dealers?” and so on. Compared to driving, where interactions with strangers is a given, introducing “random interactions” into a scenario where it’s unexpected seems to push people towards favoring legislation.

As a whole, the emergence of the new “sharing economy” is probably a net positive. Despite that, companies are certainly thumbing their nose at government regulation and entrenched players which is going to cause ruffled feathers along the way. To win the hearts and minds, companies will definitely need to manage the perception of how risky their services are both to users and non-users alike.