Rails Association Tips
Rails is one of those languages where you can infer how it should interpret code. A more simple way to word that is this: sometimes you'll be coding something for the hundredth time and all of a sudden you'll think to yourself 'I wonder if this will work' and you'll try to change a convention based on your previous experiences with that language. This recently happened to me and I wanted to share what I discovered.
We have a lot of named scopes in our app. Typically our named scopes look something like this:
In that example, our User model has_one :concierge_information (btw, definitely check out our new thredUP Concierge app). While I was creating this scope, I wondered if I could infer which 'joined_via' column I was referencing since I was querying over two tables. So I tried this:
And it worked! Much prettier, right? That example doesn't save a lot of keystrokes, but it should help keep things organized if you're joining across multiple tables and/or querying a lot of ambiguous columns (when you're query references a column name that exists on multiple models you're querying across). While I was writing this, I thought it might be nice to share some other association-related tips I've learned.
ActiveRecord Association Tips
Rails associations are awesome and they come with a lot of built-in class methods/helpers. The basic rule of thumb that I use is that if you're accessing an object's association, you probably have access to the ActiveRecord methods the association's model has. For example:
In that example, you can do any ActiveRecord query on that user's orders as if you were querying a subset of the Order table itself. This can be very handy if you have nested associations.
Object Association Tips
One that I recently came across was the built-in method for creating an associated record that is a has_one association. It ended up just being 'create_#{association name}'. It's not life changing, but it's nice to know. Here it is in action:
In case you're wondering what the has_many version looks like:
This brings up an important note about something I was fuzzy about until recently. When are these objects saved? Obviously a .create() call will write to the DB, but what about when you create/build the object outside of the association and then assign it afterwords? Here are some examples (these are all under the pretense that @user is already stored in the database):
That was helpful for me to learn as unnecessary .save calls result in additional calls to the database.
Lastly, I came across an edge case scenario that I was curious about. If you're using the '<<' operator to associate newly created objects, how do you know if the object you're creating failed? The answer is you don't. However, you can use the .push() method and it will do the same thing as the '<<' operator except that it will return true or false depending on whether the creation was successful or not.
Setting Up Sinatra with MySQL and ActiveRecord
Sinatra can be used to do a number of things. Here at thredUP, we're using Sinatra to turn some of our most used models into services accessible through an internal API. The Sinatra apps that we're building will still connect to our main Rails 3 app's MySQL database, but we'll be able to spin up multiple instances of our most used services which will help us scale as we continue to grow.
We use ActiveRecord for the models we're turning into services so when I was setting up the Sinatra app, I figured a simple Google or StackOverflow search would yield the necessary information I needed to connect the new Sinatra app to the database through ActiveRecord. Nope.
If you're looking to use sqlite3 with ActiveRecord or DataMapper, then this StackOverflow post will be your guide. For those with ActiveRecord and MySQL, here's what you have to do:
Assuming you have the 'active_record' and 'mysql2' gem installed already, all you need to do is create a config file that you require in your main Sinatra .rb file. The contents of the config file are relatively straight forward:
The env variable is important if you have different database settings for production, development, and any other environments. Here is an example of what database.yml might look like:
I know this is simple and easy, but I figure I'm not the first person to have to come across this.
Two other useful Sinatra resources:
Resizing the Root Disk on a Running EBS Boot EC2 Instance
Free up "inactive" memory on OS X
CoffeeScript for Beginners (Part 2 of 2)
My first post on CoffeeScript was primarily focused on getting CoffeeScript installed and having Node.js continuously compile your .coffee files. I touched on creating simple objects and iterating in a for loop, but this post will be all about the standard .click() handler and AJAX function (as well as some nice tricks).
Click Handlers
The .click() handler is probably the most used jQuery method and it happens to be an easy implementation in CoffeeScript. For the rest of this post, let's assume you have a JavaScript file (app.coffee) with a .setup() method that is called on page load. So somewhere in your view (after you have included the compiled JavaScript file), you have something that looks like this:
That code will ensure your app.setup() method is called after the DOM has loaded and your JavaScript is aware of every element. So what does your .click() method look like? Like this:
AJAX
AJAX, which stands for asynchronous JavaScript and XML, has become a staple for Front-end engineers. Anytime you want to talk to a database or load some foreign information without refreshing the page, you'll turn to AJAX. So for the sake of our example, let's say you want to make an AJAX call when someone clicks on a button. I'll assume you know what the JavaScript equivalent is and I'll only show the CoffeeScript:
Going the Extra Mile
There are certain best practices that can help deliver the best and most responsive experience to your users. There are two things in particular I like to do when I have a button that triggers an AJAX call.
The first thing is adding a disabled state when someone clicks the button. The user may not notice the activity spinner in the browser's tab so having a different button design that indicates a change will let the user know that the website is responding to your click. It will also give us a flag to determine if the button has been clicked so we don't make more than one AJAX request if they double click it. Keeping all this in mind, here is what the click handler looks like now:
This does 2 things. The preventDefault() call is there in case you have a valid href attribute on the anchor tag. This will prevent the link from executing. The second thing in here is adding the class 'selected' to the button and then surrounding the AJAX method call with a .hasClass check to make sure the 'selected' class hasn't been added already.
The other thing I like to do is handle the data response from the AJAX call. If something goes wrong in your controller (I'm assuming you're using a MVC framework), but all of the code executes anyways, your JavaScript is unaware that something went wrong and you'll never enter the 'error' block of your AJAX call. This why I always set an error flag in my controller that I pass back. Here is the block of code you'll need in your controller to respond to a AJAX call.
Now that our controller is passing back whether an error occurred or not, our JavaScript can handle accordingly. Here is everything coming together:
Useful Resources
Parallel tests with the thredUP app
The parallel test gem is relatively simple gem to install, that said, it took me a while to get it to work properly, here's how you do it n 6 easy steps.
1. Add the gem to the test section of the gemfile
2. Now we need to change the database.yml file in order for the gem to create the databases you need (the gem will create as many databases as the number of cores on your processor). Edit the test section of your database.yml file to look like this:
3. Next we need to setup the gem’s rake taks. To do this, add the following line to the rakefile:
That’s it! We are done with the parallel_test gem setup. In order to run parallel tests we need to prepare the database.
4. To do that we run the following command:
rake parallel:create
5. Next we need to prepare the test databases with the database schema. Before we do that, we need to run any migrations that have not been applied to the test database to do this run:
rake RAILS_ENV=test db:migrate
rake parallel:prepare
6. Last, we need to configure sphinx! Paste the following code in your test section in the sphinx .yml file
That's it!! To run the tests use the following commands
rake parallel:features # Cucumber
These commands do not work as one would expect though, so I added a rake task to make things a little bit easier. If you want to use the parallel test gem just use:
rake thredup:faster_cucumber
From the Dev Couch: Redwood, Backbone, and Capfire
Apps to Improve your Workflow
App: Redwood
Link: redwoodapp.com
I'm about to gush: <earmuffs> this app is fucking awesome </earmuffs>. I hate searching for things - it's a complete waste of time. A while back I installed Alfred App to allow me to 'jump' straight to launching an application after hitting a hot key and it's a huge time saver (not to mention I never have to organize my application folder again). So Alfred is for your apps, but what about for all your files? Enter Redwood.

If you're like me, you have emails, messages, and attachments scattered throughout Gmail, Basecamp, and Dropbox. Only Dropbox is mounted locally and I use Thunderbird for my mail needs so I have to log into Gmail to search and I just pray that I'm searching on the right Gmail account. Redwood is a local app that allows you to add Gmail, Basecamp, PivotalTracker, and Google Docs accounts to and gives you the ability to search across all of the them.....amazing. So I have Alfred mapped to Ctrl + Spacebar, Redwood to Opt + Spacebar, and Spotlight to Com + Spacebar. Hello efficiency world.
Learning About New Technology
Technology: Backbone.js
Example: todos.js
Homepage: documentcloud.github.com/backbone/
GitHub: github.com/documentcloud/backbone/
If there was a ranking for the adoption rates of new (so excluding jQuery/Prototype) JavaScript frameworks/libraries, I would bet Backbone.js is second only to Node.js.

Backbone.js allows you to create a MVC of sorts inside your JavaScript. If you're anything like us, a lot of the functionality on your website is handled with JavaScript. Whether it's AJAX posting, error checking, or complicated modals, odds are you've dealt with JavaScript spaghetti. So similar to Rails, or any other good MVC, Backbone provides you with a framework of how to organize, write, and structure your code. It's sort of hard to explain, so here's the official summary of Backbone.js:
With Backbone, you represent your data as Models, which can be created, validated, destroyed, and saved to the server. Whenever a UI action causes an attribute of a model to change, the model triggers a "change" event; all the Views that display the model's data are notified of the event, causing them to re-render. You don't have to write the glue code that looks into the DOM to find an element with a specific id, and update the HTML manually — when the model changes, the views simply update themselves.
I haven't created anything with it yet (my learning plate runneth over), but give it a try and let me know what you think.
Rails Gems Worth Checking Out
Gem: Capfire
Link: rubygems.org/gems/capfire
The thredUP Dev Team has started to use Campfire as our chat collaboration tool of choice. Questions, Github commits, and countless emoticons dominant the chat room. As a development team of 10, we come across many issues about learning different parts of our app or programming language specific questions and it doesn't scale to just ask one person every question - so we post the question to the Campfire chatroom and let the first available person answer it. So far it's working out really well. So where does Capfire come into play?

Capfire is a gem that automatically posts a message to your Campfire chatroom after someone (namely someone who has Capfire installed) deploys your app. We already have Github hooks in place for pushes to remote repositories, but I think it's valuable to know when new code is being deployed to an app - especially if you have code in that deploy. To install Capfire, check out these install instructions as they're the best I came across.
The Power of Lambda, Bindings and Blocks
I've been slowly making my way through the Dave Thomas series of Advanced Ruby vodcasts. The series has been very enlightening as I'm learning a lot of powerful tools that Ruby offers as a programming language. A particular topic that he covered that sort of blew my mind was Ruby bindings and lambda.
Lambda
Lambda is something I've been working with for a while. The two main ways we utilize Lambda in the thredUP app is with named scopes and dynamic hash values. Examples:
The examples above are pretty standard usage of lambda. What I didn't know is that you could do something like this:
I think this is particularly useful in the event you're lambda block takes in options. Typically I see that people construct an options Hash object and then pass it in. By denoting the asterisk (*) before the last parameter, it allows you to just pass in all your options within your method call. If you have a lot of options, the call will look unwieldy and the Hash object creation is probably best.
Bindings
Yesterday was the first day I had ever heard the term bindings within the context of Ruby. Although I'm still trying to think of useful implementations of bindings inside of our thredUP app, the knowledge of how to use them should become a handy tool when brainstorming solutions in the future. My understanding of a binding is that it allows you to hook into's a block execution and retain the ability to enter into that block through the hook at will. Ruby-doc says that bindings 'encapsulate the execution context and retain this context for future use'. I like my definition better.
So once you create a binding, you're able to invoke said binding using the Kernal#eval method. Here is a simple example:
One could easily argue against the practicality of this example, but it was the best I could come up with in a couple of minutes. This particular binding gives you access to an instance variable of a class without setting up an attribute accessor. Also, since eval() is used, dynamic construction of objects opens up a little world of possibilites. If the EMPLOYEES constant contained classes instead of strings, eval() could dynamically create new objects for those classes (or access methods of those classes) within another class (such as Thredup) with the use of a binding.
It's a bit mind-numbing to think about good use cases of bindings, but it's a nice addition for developer's toolbox. You never know when you might have to throw every tool in your toolbox at a problem to arrive at a solution - so every tool counts!
Blocks
I came across something that I thought was really interesting. A method can accept a block if you denote the parameter name with the '&' symbol. The block will come in as a Proc.new() object (almost identical to a lambda) and will therefore require the .call() method to invoke the block that was passed in. For once, I have a practical example of how valuable this is:
This cache_me method could be used as a tool to cache or retrieve (fetch) a metric based on a cache key and an expiration. The key and expiry could also be combined into one dynamic key if you want to add some syntactic sugar to your metric pie.