All Posts in Ruby on Rails
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.
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" />
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)
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
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 => 'firstname.lastname@example.org' 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.
“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?
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.
Let’s consider the Rails test suite. What’s our flight of fancy? Super duper fast tests. Once we set our sights on lightning fast tests, we bring them to life, nevermore accepting pokiness as threadbare reality. Thankfully many smart people have done great work to bring this closer to being, but not without a touch of controversy.
Background on Test Performance
Executing a single (trivial) RSpec test against an empty Rails app is on the order of several seconds. This performance is not the product of anyone’s fantastical dreams, of course, but a function of reality. The Rails stack takes time to load and there’s no obvious way around it. Except, of course, to go around it. All of the sudden tests are several orders of magnitude faster. That’s the trick. Only use Rails when necessary and life is beautiful. Which begs the question, when exactly is Rails necessary in a Rails app?
Rails as Detail of Project
DHH chuckles at the notion of Rails-as-detail: "… Web apps don’t wake up in the morning and don an iOS suit." And it's true, no Rails codebase will ever end up running on an iPad mini. That said, how many people would benefit from lopping off functionality into lightweight independent services but have little idea how to begin? Generally speaking, who doesn’t want a better understanding of the entanglements of an application? After all, clear definition of dependencies is a central challenge in programming—it's a core tenet of useable design.
Quick Example of Rails as Detail
Take a module that lives in Rails whose mission in life is to talk to a third party API. I recently set out to extract something like this from Rails. It required one piece of Rails (the from_xml method) to parse the response:
response = Hash.from_xml(http_response)
So I added the single dependency to the api spec (and learned a bit of Rails trivia in the process):
In this simple but common case, the entire Rails stack is obviously not needed to test the wrapper. By decoupling from the entire framework testing is quick and we’ve outlined the specific dependency for the benefit of posterity.
Controversies be Darned
It's true. As programmers we should be happy about and embrace progress in the form of:
1. Orders of magnitude performance improvements. Goes without saying. Orders of magnitude efficiencies are ultimately what we’re concerned with in various forms every day. Does it take 10 people to ship an order or just 1? Does it take 500 ms to execute a test class or 5 minutes?
2. Clearer dependencies. Asking classes to outline their dependencies to Rails and elsewhere leads to clarity. Rails is a big framework. Seeing the forest for the trees drives a better understanding of the framework and its relationship to the domain logic.
tl;dr Actors in Today’s Flight of Fancy:
Rails = Chuck wagon with all manner of useful provisions, but heavy.
Fast tests = Beautiful pastoral field, but far away.
Independence = Awesome horse that gives you a ride and teaches you lessons along the way.
Take the ride, enjoy the field, pick some flowers.
In Ruby on Rails 3, non-database functionality was moved from ActiveRecord to ActiveModel. This is great since it makes it easy to use all the ActiveRecord niceness we’ve come to love for non-ActiveRecord models.
My favorite bit of functionality moved to ActiveModel is localization. (Well, validations are actually my favorite, but localization is a close second.) Rails has robust localization support though the Rails Internationalization (I18n) API. Hopefully you’re already using it, if not for creating multi-lingual sites, then at least for keeping custom attribute and model names consistent between labels, errors messages, etc.
The Rails guide does a great job of walking us through the basics of localization and using it with an ActiveRecord object, but falls short when looking at ActiveModel localization. So let’s dive in…
Let’s say we have the following namespaced model:
attr_accessor :name, :price, :image_url
As you can see, we’ve already included some ActiveModel modules. Conversion gives us useful methods including to_param and to_key. AttributeMethods gives us lots of accessor and attribute related goodness. And Validations gives us, well, validations.
Let's look at the attributes. The "name" and "price" attributes will humanize nicely to "Name" and "Price" but I want to refer to "image_url" as "Puppy Pic", not the default humanization "Image Url". This looks like a job for localization!
Sign up for our monthly newsletter to stay up to date on the latest tech tips from Table XI and to receive exclusive invites to events