Table XI Blog

Ruby on Rails

May 22, 2015No Comments

Ruby Rogues and the Double Life of Tests

Book cover for "Rails 4 Test Prescriptions"

[Authors note: So, I wrote this in December, and promptly forgot about it for five months. It happens. I've annotated slightly.]

I was excited to be a guest on Ruby Rogues this week [note: actually last December] to discuss my book Rails 4 Test Prescriptions, available now as an ebook, and coming very soon [note: available now]  as a physical object that you can buy or, say, give as a gift to all your friends. [note: still a great idea, please buy for all your friends].

Read more

September 23, 2014No Comments

Stop Missing Files in Your Assets Precompile

Rails Asset PrecompileWell, it’s been a good couple of days. You’ve been productive and finally released that tricky feature. It got pretty complicated, but you knew this was happening and were super careful to test along the way. A lot of the work was done in a new JavaScript file you added to your Rails project. Everything is working well for the team testing this locally (and we tested this thing upside down and inside out). Excellent. Now, it’s time to get this in front of your client. Time to push this new stuff to the server. Deployment successful and the fancy new thing you just built isn’t working. Sounds familiar doesn’t it?

Read more

June 12, 2014No Comments

Rails 4 Test Prescriptions: Build a Healthy Codebase

Your Ruby on Rails application is sick. Deadlines are looming, but every time you make the slightest change to the code, something else breaks. Nobody remembers what that tricky piece of code was supposed to do, and nobody can tell what it actually does. Plus, it has bugs. You need test-driven development, a process for improving the design, maintainability, and long-term viability of software. Table XI's Senior Developer & Agile Coach, Noel Rappin, can help.

Read more

February 13, 2014No Comments

Greg Baugues Talks Devs & Depression on Ruby Rogues

Ruby Rogues logoRecently, our old colleague Greg Baugues chatted with the guys at Ruby Rogues about a subject we think is one of the most important facing our industry today: the prevalence and stigma of mental illness in the developer community. A programmer who struggled for a long time to identify and deal with his own ADHD and Type II Bipolar, Greg has given several talks about his own experiences and how to get help if you or a friend is suffering from depression or another kind of mental illness.

Read more

July 9, 20131 Comment

FoxySync: How to Synchronize Your Website with FoxyCart

FoxySync logo.If you've ever done an e-commerce integration, then you know what a pain it can be. Traditionally you'd build a shopping cart, create a checkout workflow, and integrate with a third party payment gateway. Ultimately you spend a lot of time writing and testing new code for an old task. I've done a few of these integrations, and the last time I did I tried something new: FoxyCart.

I wanted to try FoxyCart because it would allow me to outsource the shopping cart, checkout, and payment gateway integration. As a result I could clean up my code base, reduce my maintenance costs, and setup for an easy payment gateway switch in the future. Making FoxyCart work with my Ruby on Rails app, however, was not a cinch. There were no Ruby gems to work with and examples in Ruby were sparse. I knew I'd have to figure out a lot of the integration on my own so I thought I'd make it easy for the next Rubyist and cut a gem out of the work. That gem is called FoxySync.

FoxySync encapsulates four FoxyCart integrations: cart validation, single sign on, XML data feed, and API communication. Using all together fully synchronizes and secures all communication between your app and the FoxyCart service. Let's take a look at each.

Cart Validation

Since FoxyCart knows very little about your products, it depends on you to post any metadata—including price—when customers add items to a cart. As a default, the metadata is stored as plain text in the web page where the “Add to cart” button lives. This is risky because, if someone knows what they're doing, they could change the price of your product before it’s sent to FoxyCart. To prevent such tampering, FoxyCart offers HMAC product verification, or what I like to call cart validation. The feature works by validating a hash on each piece of metadata to ensure authenticity. FoxySync makes this easy by providing a helper method to generate the correct HTML form variables.

include FoxySync::CartValidation
cart_input_name 'code', 'mai', 'mai'
# results in <input type="hidden" name="code||5651608dde5a2abeb51fad7099fbd1a026690a7ddbd93a1a3167362e2f611b53" value="mai" />

Single Sign On

FoxyCart keeps an account for each user that checks out on your site, but with a good integration, those customers shouldn’t even know they’re using it. That being the case, it's weird to ask them to reauthenticate on the checkout page if they’re already logged into your site. FoxyCart's single sign on feature prevents this weirdness by asking your application to acknowledge authentication before the checkout page is displayed. FoxyCart makes a request to your site and your application redirects back to FoxyCart. FoxySync helps with this handshake by providing a helper method to generate the redirect URL.

include FoxySync::Sso
redirect_to sso_url(params, user)

XML Datafeed

FoxyCart's transaction datafeed feature ensures that your application is notified of sale details after each successful checkout. When enabled, FoxyCart will post to your application an encrypted XML document and expect a particular response. FoxySync helps with this feature by handling the XML decryption and providing a helper to generate the appropriate response.

include FoxySync::Datafeed
receipt = []
xml = datafeed_unwrap params
receipt << xml.customer_first_name
receipt << xml.customer_last_name
receipt << xml.receipt_url
# etc
datafeed_response

API Communication

FoxyCart has a robust API that lets you manipulate and retrieve data about your store, customers, transactions, and subscriptions. FoxySync makes working with the API dead simple, so you can easily access this powerful feature.

api = FoxySync::Api::Messenger.new
reply = api.customer_get :customer_email => 'foo@bar.com'
reply.customer_id # is the customer's FoxyCart id

FoxyCart is a great service for adding sophisticated e-commerce to your website without having to do a lot of the hard work. However, FoxyCart still needs to be integrated, and for Ruby on Rails apps, FoxySync makes that pretty easy.

Want all the best React Native tools in one stack?  Download your free copy of our own mobile development stack

July 2, 2013No Comments

Russian Doll Caching in Rails

Five russian dolls.Russian dolls: not just a knickknack you bring home from Moscow or a short-lived Lifetime reality TV show. It’s a powerful caching technique that we used to make the new RogerEbert.com fly. Russian Doll Caching is the default in the new Rails 4, so it’s best to start getting used to it.

Traditional page and action caching are powerful and speedy, but the control they offer is often coarse and unwieldy. Say you want to update some text in the shared site header. You now have to invalidate every single page on the site. All those pages will have to be fully rendered the next time someone visits them.

Expiring expire_fragment

If you’re using traditional fragment caching, you’ll find yourself face-to-face with the cache often. Any time you add a new fragment, you better go add an expire_fragment for anywhere where it might get updated. In a cache store like Redis or FileStore you can use regular expressions to delete a series of keys, but that process is very slow since behind the scenes the store is comparing every single key to the Regex. In Memcached, you don’t even have that and thus need to delete every single key individually.

Enter the obligatory Phil Karlton quote: “There are only two hard problems in Computer Science: cache invalidation and naming things.” In this new caching paradigm, we build on fragment caching, but flip cache expiration inside out. The beautiful secret to Russian doll caching is you never explicitly invalidate anything. Never again will you need to expire_fragment. Instead, we just use a brand new key.

We’ll get into the details of this soon, but like a proper Matryoshka doll, let’s start from the outside in.

An Example View

Here is an example from RogerEbert.com. I’m simplifying the code for the sake of brevity, but all the salient ideas will still be there. For reference, we are using Mongoid as our ORM on top of MongoHQ and the Dalli memcached store over Amazon’s Elasticache. If you’re using ActiveRecord, these techniques still apply, although the syntax might be slightly different.

The basic organization of the site is pieces of content organized within channels. A piece of content belongs to primary channel.1

[gist id=9ba513aff504877bfa21 file=ebert-blog-post.rb]

Here’s a channel listing taken from www.rogerebert.com/festivals-and-awards and below it, simplified view code:

Screenshot of the Roger Ebert's Channel's Page
[gist id=9ba513aff504877bfa21 file=channel.haml]

What's the Key?

The cache view helper takes an array as its first argument. It concatenates all the pieces together, calling #cache_key for any objects that respond to that method. We’ll get to cache_key’s implementation soon, but for now, know that each model object has a unique cache key. A naïve implementation might be "#{self.class.model_name}/#{id}"2.

[:index, :page, @contents.current_page, @channel] would create a cache key like views/index/page/1/channels/123 and nested within that cache, [:listing, content] would turn into views/listing/contents/12345. An advantage of this is it allows us to easily share a cached fragment across pages. If the piece of content falls off to the next page and we have to re-render the main index, we can still use the other individual content fragments from cache.

This still leaves us with keys that must be invalidated. How do we account for that? What if #cache_key were smarter than our previous implementation? And, what if every model instance had some persistent attribute that gets changed every time the instance gets updated. It’s a good thing we’ve got updated_at handy, and the default implementation of #cache_key already takes advantage of this.

If you look at the source, you’ll see that the key is a combination of the model name, its ID, and its updated_at timestamp. So if you call #update_attributes or #save on a model, that updated_at field will get the new time and voila! #cache_key will be different the next time you ask for it.

[gist id=9ba513aff504877bfa21 file=cache-key.rb]

So a normal ActiveRecord cache key might look like contents/1234-20130519024351. Mongoid will look a little crazier: contents/5194dd8d4206c510c2000001-20130528101518.

Combine that with a context like :listing, and you have a unique cache key for each fragment that will be updated any time you update the object.

And thanks to touch: true that we have on the belongs_to :primary_content association, any time you make an update to the piece of content, it will also touch the channel and give it a new updated_at timestamp.

So, imagine that we have views/index/page/1/channels/1234-20130528101518 as a cache key. We’re still having to look up the channel from the database, but we don’t have to hit the database to find the @channel.contents association (it’s still just a Mongoid::Criteria or ActiveRecord::Relation at this point waiting to be lazy-loaded). If we update the title of one of the pieces of content, we get a new cache key for the content and for the channel. The next time someone visits the page, we do have to hit the database to get the contents' updated_at fields, but we only have to render 1 out of 10 of the :listing fragments (there are ten posts per page); all the rest are fetched from the cache.

What about the old cached fragment? Don’t we need to delete it? The short answer is “who cares” and “no.” If you’re using a store like Memcached and it needs more space, it will automatically purge any key/values that haven’t been accessed recently.

There are still things to be aware of, such as what happens if your code changes; how do you invalidate the cache then? That's where cache digests come in, and a subject for another post.

In the meantime, start nesting your fragments and speed up your site's performance!


1 A piece of content can belong to additional channels, but I’m leaving that out for simplicity. The primary channel is the important one, since it's what we use for determining the canonical URL of a piece of content.

2 In fact, this is the return value of one of the three cases in the default cache_key implementation.

May 15, 2013No Comments

Highlights from RailsConf 2013 – Portland

“Head West!” This is how DHH described the pioneering spirit of the Rails community in his keynote that kicked off RailsConf 2013. I recently made my own journey west from Chicago. So it was fitting to attend the conference in my new hometown of Portland.

There were many outstanding sessions, including a talk on Rails vs the Client Side by Table XI’s own Noel Rappin, How to talk to Developers by Ben Orenstein, and The Magic Tricks of Testing by Sandi Metz. Topics ranged from integrating NoSQL with your Rails app to designing social media apps for a world that is not “normalized.”

Now is truly a great time to be a Rails developer, and attending the conference was a fantastic way to discover new resources. Rails 4.0 release candidate 1 just came out. There are good learning tools available, including the podcasts RubyRogues, Ruby5, and Code School. There are also great tools for evaluating the quality and security of your code like Code Climate and New Relic. If your company is hiring or job searching, Developer Auction is a resource that takes a creative approach to connecting employers with job seekers.

With over 1,500 attendees, the “hallway track” was packed. I met some really interesting people and had a great discussion with Chuck from Portland Code School about how to get more women involved in the local Rails community. Women are a strong part of the Rails community and were represented at the conference by groups like Rails Girls and Women Who Code. It was also inspiring to see Sandi Metz and the founders of RailsGirls: Linda Liukas, Pia Henrietta Kekäläinen, and Karri Saarinen recognized as Ruby Heroes.

In addition to the sessions, RailsConf 2013 hosted some of the best lightning talks I’ve ever attended. I highly recommend checking out the following:

  • Nick Quaranto and Miles Forrest both gave talks about launching Ruby meetups. Nick started openHack and the Buffalo Ruby group. Miles successfully started his own local Ruby Brigade. He had been commuting from his hometown of Chillowack, BC, after three failed attempts drove him to commute all the way to the Seattle Ruby Brigade.
  • Chris Morris, in his talk on Technical Intimidation, challenged us not to be intimidated by people who know all the things, but to learn from them.
  • Jon McCartie gave a strong presentation on purposeful code. He challenged us to find ways to apply our skills to tasks we value.
  • Yoshiori Shoji was inspired to use gem-mirror to keep on hacking, even during a 10-hour flight from Japan.
  • JC Grubbs spoke about apprentices, and how to teach and value people.
  • Andrew Harvey talked about shaping company culture.
  • David Padilla really summed it up when he said conferences are about content, but they are also about people.

I definitely came out of the conference inspired to learn more, code more, and become more involved in the awesome Rails community. I’m looking forward to next year’s RailsConf, which will be back in Table XI’s sweet home Chicago!

What were your favorite parts of RailsConf 2013?

Want access to more articles like this?  Subscribe now to stay up to date on the latest from Table XI 

May 14, 2013No Comments

Rails vs. The Client Side: XI to Eye

XI to Eye logoTwo completely different ways have emerged for using Rails as the back-end to a rich client-side JavaScript application:

  • The 37Signals "Russian Doll" approach, used in Basecamp Next, where the server generally returns HTML to the client. This approach uses aggressive caching and a little bit of JavaScript glue to keep the application fast.
  • The "Rails API" approach, where the server generally returns JSON to the client, and a JavaScript MVC framework handles the actual display.

Which of these will work for you? For this week's XI to Eye, I've posted my RailsConf presentation on the topic.

Also, if you like this talk, my book Master Space and Time With JavaScript has much more detailed information on using JavaScript effectively, including a work in progress on Ember.js.


Watch live video from Confreaks - Live Streaming on Justin.tv

Want access to more articles like this?  Subscribe now to stay up to date on the latest from Table XI 

May 8, 20133 Comments

Tales on Rails: The Three Little Devs

The Buggy code giving a presentation to the Three Little Pigs

You know how the story goes: Once upon a time, there were three little devs. Smart and determined, the three developers set up a new Rails app.

The first little dev, the youngest and littlest, wrote a handful of ActiveRecord conditions in SQL.

 

[gist id="4bd6c8ea3c3e4be0ccdd"]

All was well, and the queries worked! So it was, and so it continued, for several minutes. But as the littlest dev carried on, innocently combining his scopes, he was interrupted by a big, bad bug. The bug snarled, "Little dev, little dev, just call it quits!"

The littlest dev was having none of this. "Not by the code in my github commits!"

"Then I'll huff, and I'll puff, and I'll raise an exception!" shouted the bug, who proceeded to do just that.

[gist id="5126e7b682aef787e628"]

The littlest dev fled in terror to the chat window of his brother, the second little dev, who was a little bit wiser and a little bit bigger (relatively speaking, of course). He nodded solemnly as his younger brother explained what had happened.

Putting on his bravest demeanor, he announced, "Let's refactor, and chase off that big, bad bug once and for all!"

They worked tirelessly for minutes upon minutes, using the squeel gem to replace their old SQL conditions with robust, readable Ruby code.

[gist id="45429d859f7d06bf69c0"]

Just as they finished adding in a new query, the big, bad bug arrived yet again, displaying an uncanny sense of plot and timing. "Little devs, little devs, just call it quits!"

"Not by the code in our github commits!" came the obvious response from the little devs.

"Then I'll huff, and I'll puff, and I'll raise an exception!" roared the bug. Sure enough, he huffed, and he puffed, and it turned out that the devs had made a typo in their new query, a direct result of too much code duplication.

[gist id="bdfa4f9cea58dbc6f3b1"]

The two little devs opened a group chat with their eldest brother, the third little dev, who was much wiser and much bigger (relatively speaking, of course). He nodded solemnly as his brothers explained what had happened. Confidence radiating from his monitor-tanned face, he spoke slowly and calmly, "Let's refactor, and chase off that big, bad bug once and for all."

The brothers worked tirelessly for at least a few seconds, using ActiveRecord::Relation's merge method to reduce the duplication of logic in their queries.

[gist id="d545f3737f6e34accc7f"]

The big, bad bug did not show up again, and the three little devs lived happily, for at least a little while.

I'm sorry—you don't think this sounds familiar? The version you know involves pigs building houses made of straw, sticks, and bricks? And a wolf with improbable lung capacity? This is no time for make-believe; I'm telling the story the way my father told it to me, and his father told it to him.

Like all good stories, this one has a moral: Use squeel and ActiveRecord::Relation#merge to reduce the complexity and duplication of your ActiveRecord queries. Who knows? Maybe you too can live happily, at least for a little while.

Want access to more articles like this?  Subscribe now to stay up to date on the latest from Table XI 

December 28, 2012No Comments

Pragmatic Flight of Fancy in Rails Testing

A common TDD concept is that you write tests targeting the most optimal API imaginable, rather than contorting your code around current production realities. It’s possibly the most practical form of flight of fancy anyone has ever considered. Run free in a field with your API before you build retaining walls to thwart mudslides. The resulting code is much better because you work toward the best possible experience, deferring details for as long as possible. It’s amazing how well the process works in all types of contexts.

Read more

Table XI

328 S. Jefferson St.
Suite 670
Chicago, IL 60661
312.450.6320

Workshops

Give your team new problem-solving techniques with our innovating workshops and check out our event series.

GoodFirms Badge