Integrating your rails app with Dropbox

By Chris Homer - @chrishomer

At thredUP, we recently started using dropbox to do more than just store and share files among employees.  We've now integrated it with a couple of our applications so that certain data sets get archived there.  We used to just send them by email if they were small enough or save them to a server and then download them manually.  Now, with dropbox, they get dropped in a shared folder and the people that need access, have it.  

Implementing this integration had a couple hiccups along the way and I want to share how we did it in this post.

First, we used the dropbox-sdk gem (https://www.dropbox.com/developers/core/sdks/ruby) to handle most of the heavy lifting but you still need to implement a workflow to gain authorization with dropbox.  

We wanted to be able to authorize a conneection and persist the session to the database so we could restore it and work with dropbox without having to reauthorize again.  To accomplish this, we wrote a model for storing a users authorization session information:

As you can see, it's a fairly compact class. Here's how to use it:

With this wrapper class it's really that simple.  You could always implement a simple scaffold for this class and customize it to handle the auth workflow through the web browser - we don't add accounts that often, so didn't take this extra step.

A few more client use tips:

Hope this helps you integrate with Dropbox in your own applications!

Setting Up Sinatra with MySQL and ActiveRecord

by Dan DeMeyere - @dandemeyere

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:

The Power of Lambda, Bindings and Blocks

by Dan DeMeyere - @dandemeyere

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.

From the Dev Couch: All Ruby Baby

by Dan DeMeyere - @dandemeyere

Rubyflow is a great Ruby blog aggregator. I subscribe to their RSS feed and every day there are multiple posts that either pique my interest or are relevant to gems or technology that I work with. I don't have time to read all of them everyday so I bookmark all the good ones and set aside a couple of hours every week to parse through them all. Featured in this post are the articles that I learned something from or determined are worth saving for a later date as it could become handy in the right situation.

Realtime Data Overlays Using Google Maps

The Ghostly Map
A couple of months ago the thredUP dev team wandered over to Cloudflare's office in SOMA to celebrate their recent achievements. While we were enjoying a couple of beers, we stumbled across a 10-foot projector screen displaying a realtime geo-mashup of their service in action. My colleagues and I all looked at each other and knew instantly we had to do something similar. While our version is still on our 'fun to-do list', this post on Stac's blog is a good walkthrough about how to make a realtime maps mashup with Rails 3. They cover using Rails' cache store API, use of Backbone.js, Underscore templates, GeoKit, and the Google Maps API. Read more →

Automatic Page Loading

Endless Page Scrolling with Rails 3 and jQuery
This has to be the coolest post I came across. Do you ever wonder how Facebook only displays a certain number of comments or status updates and when you approach the bottom of the container, they automatically add more? Well, this is how you can do it. It's a relatively simple implementation using jQuery to attach a custom handler on an element that makes an AJAX call to your Rails controller to append more data to the element. The only required file is his custom jQuery library, which can be found on GitHub here.

Altering Rails' Naming Conventions

Pluralizations and Singularizations (Inflections) in Rails 3
When I first started learning Rails, I found the naming conventions difficult in routes, controllers, and models. What was plural, what was singular, and what stayed the same - i.e. if the model is history.rb, is the controller histories.rb? In general, Rails is pretty good about getting that kind of stuff right, but if you want to override how they pluralize or singularize anything, then this post will be great for you.

Optimizing MySQL

Tuning MySQL - Innodb, Buffer Pool Sizes, and Rails Stack Server Advice
I'm not going to even pretend I know 10% of what's going on in this post. Even though it's way over my head, I have to imagine every person who works on a MySQL-based app can read this post and have some valuable take-aways. Did you know you can log slow queries by changing performance values in your MySQL my.cnf file? You can even change how many seconds constitutes a long query for your app. On top of that, you can log queries that aren't using indexes. Now that's pretty slick. There is also good advice for those using a Rails/Apache/Passenger/MySQL/Memcache stack (which is what we use at thredUP). Read more →

Notable mentions

Polishing my Rubies: Instance Variables & the 'self' Object

by Dan DeMeyere - @dandemeyere

If you're not interested in learning about Ruby, this post may not be valuable to you. Proceed at your own dorky will.

Super quick backstory: Ever since joining thredUP back in early September this year, I've been new to Ruby. I spent my first couple of months learning our app and gaining a functional knowledge of Ruby on Rails. 9 months later, it has become time for me to go back and back-fill the fundamentals of Ruby that I missed.

In my opinion, having sound fundamentals in anything, from Ruby to basketball, is what allows you to consistently produce quality results. Luckily for me, thredUP schedules in a healthy amount of time to be designated for professional development. This post is the first in a series of many that will catalogue what I previously did not know or were ambiguous at how they worked behind the scenes.

Please take a look at this example I wrote:

This is mock class that will demonstrate how using self in Ruby works in the context of instance variables. If you read through this class, you'll notice it's pretty straight-forward. Take a minute and write down what you think will be outputted when lines 28-36 run and don't cheat by looking at the bottom of this post.

Don't worry, I'll wait.

Once you're done, compare your results to the code at the bottom of the post. If you were anything like me an hour ago, you would have made some wrong assumptions. So let's figure out why. First, let's define some vocabulary.

  • self - this refers to the current object in Ruby.
  • explicit receivers - the object you are setting to be invoked upon in Ruby.
  • instance variables - commonly denoted with the '@' sign such as @variable. These types of variables are not public (their scope is confined to self), but they are global (broader scope accessibility than standard variables).

That might not seem so tricky, but if you're not careful when using instance variables then you can find yourself accessing or overwriting the wrong variables. So let's dive in head first. On line 28, when we print self out to the screen, the output will show the class name Dolphin. Simple enough - we're in class Dolphin when it's called so there's no surprise there. When we output @display, you'll notice 'no dolphin specified' is printed out. Since that's its original value set on line 2 and no other call has been made yet, this shouldn't be a surprise either.

Next we call Dolphin.bottlenose on line 31 to build our new Dolphin object, which we set to a standard variable named dolphin. Here's where it gets tricky. When we invoke the display method on our dolphin object, we are setting dolphin as the explicit receiver, which will change the object that self is pointing to and therefore the scope of @display changes. You'll notice that the first time we output @display from within the display method, the value is blank or nil. Weird, huh? It's because @display in the context of your dolphin object (i.e. #<Dolphin:0x1001370d0>) is different then in the context of Dolphin. The simple distinction between what the current explicit receiver is set to determines this. If it's still a little confusing, read on as I'll clear it up.

After we finishing outputting within the display method, @display now holds a new string value when the dolphin object is the explicit receiver. Line 34 will demonstrate the difference as it will once again print 'no dolphin specified' since the self object is now referencing the class Dolphin again.

So why is this useful? Well, take a look at what line 36 outputted. You'll noticed that even though @display was not set within the color method, we're still able to access the contents of the instance variable that was set within the display method since the color method was invoked on our individual dolphin object, which changed the context of self again.

Hopefully this was as helpful to you as it was to me for learning how to differentiate how instance variables are set, accessed and scoped. Here is the source code with the output directly following it to make it easier to read what's going on: