Chrome Developer Tools Tricks & Tips

by Dan DeMeyere - @dandemeyere

If you're a web developer and you have spent time writing JavaScript and/or styling with CSS, odds are you're familiar with Chrome Developer Tools (CDT). When I discovered CDT, my front-end productivity sky-rocketed. Editing CSS on the fly, inspecting HTML, and interacting/debugging with the page's JS console have become more engrained in my day-to-day workflow than any other development tool I use. I love TextMate, but if someone put a hypothetical development gun to my head and asked me to choose between CDT and TextMate, I would be asking around for good a Vim tutorial if you know what I mean.

Quick disclosure: all of the tricks and tips below have been tested with CDT, but there's a chance they won't work with FireFox's Firebug Add-on.

JavaScript Debugging

There are three very useful tools in CDT to debug your JS. The first is the most obvious - the interactive JS console. When you open up the developer tools (⌘ + Alt + I), the interactive JS console resides with the 'Console' tab. You can also press (⌘ + Alt + J) to dual-load CDT and the console tab. This console allows you to interact with the page's DOM. You can execute any JavaScript you want here and also interact with objects (like the window object or any local objects you've defined) and inspect their contents/functions. One important note is that when this console loads, the DOM has loaded as well, which means if you're using jQuery and it's working on the console, but not in your source file, you're probably missing a jQuery $.ready() wrapper.

The second debugging tool is fairly new to me. If you click on the 'Scripts' tab and choose one of the JS files included in the page, you're able to add breakpoints to the code by clicking on the line numbers. Once the breakpoints are added, you can step through every breakpoint. It can be tedious tracking down the code you want to put the breakpoint in if you have many files. It's especially painful if you're writing in CoffeeScript as the line numbers you're editing in your .coffee file differ from the compiled line numbers of the same .js files (what you see in CDT).

Last week a colleague of mine, Wilson Collado, told me about the 'debugger;' call. If you put 'debugger;' in your JavaScript, it's the equivalent of putting a breakpoint through the scripts tab. It's a really useful trick that can save you a lot of time. One last thing about the scripts tab - make sure you take a look at the call stack information panel (located on the right side of CDT's scripts tab). In this panel you can also inspect all the local variables at the time in which the breakpoint/debugger was reached. Very helpful when stepping through your JS.

I would be remiss if I discussed JavaScript debugging and didn't mention the 'console.log()' function. In your JS, you can pass any object to console.log and it will print out the object on your console when the code is executed. You can then inspect the object to look at its value/properties. Simple, but very useful. In addition to log(), console also has warn(), info(), error() and assert() functions. Assert is really nice as it will evaluate the contents of whatever is passed into the function as a boolean. Beware that leaving in console calls will break your JavaScript in Internet Explorer, so make sure to take them out before you commit your code.

HTML/DOM Tricks

If you right click on any part of a website in Chrome (with the exception to a website built in Adobe Flash), there's an option called 'Inspect Element'. This is any front-end dev's bread and butter. You can view/edit HTML, traverse the HTML hierarchy, view CSS for any HTML element...the list goes on. For the most part, inspecting the HTML is elementary (yes, pun intended), but did you know that if you select an element, go to the console, and type '$0' - the last element you inspected is now tied to that variable? I didn't. Will User dropped that gem on me last week. The $ command dumps previously selected nodes, try typing $2, $3 and so on.

Here's another one that is news to me. There are certain CSS selectors that are used on every custom-styled button (or link). They are ':hover' and ':active'. If you have a button that is supposed to change it's image when you cursor over it or press it, you're invoking one of these selectors. It's a pain to style them though because when you hover over the element, the CSS properties show but you can't edit them without moving your cursor over to the CSS property (it's hard to explain, just try to do it and you'll see what I'm talking about). Enter the 'Toggle Element State' feature. In the CDT CSS pane, click the 'Styles' arrow and then click the button with the dotted square with a cursor in the center of it. Now you can toggle these selectors. See below:

Console DOM Tips

Lastly, let's go over some tips that involve both the console as well as the Document Object Model (DOM). Fire back up that console press (⌘ + K), which will clear the console. Grab an element off the DOM with jQuery (or do $0 if you've recently inspected something). Now call 'dir()' and pass in the element. As you'll notice, 'dir()' will print out every attribute/property that exists for the element. There are definitely some properties I didn't even know existed after using it for the first time.

Let's say you're generating something on the console. Maybe a calculation or you're scraping a page for some text. Did you know that you can pass in JavaScript to the 'copy()' function and it will copy the result of the JavaScript to your clipboard? The potential uses are probably not obvious, but it's another solid tool to keep in that JavaScript debugging toolbox.

If you have some CDT functions/tools/tricks that I didn't list, please share them in the comments.

Design Inspiration

by Dan DeMeyere - @dandemeyere

Being inspired is one of the strongest types of motivation for me. When I see something great, I can become inspired to build something of equal caliber or at least put more effort into what I'm currently working on. Sometimes the execution of an idea can be just as inspiring as the idea itself. One great example of this is Path. The more you use their app, the more you can appreciate how much attention to detail was involved in building the app. Every interaction, every pixel, is perfect. It's hard to put into words the experience that is felt when you use something and everything is just 'right'. 

So just in case you need some inspiration, here are some websites and Dribbble shots that I find inspiring.

www.BlameStella.com

Other than giving thredUP a great score, Stella's website has nice, non-obtrusive color tones that emanate an inviting feeling. It's refreshing to see a website that isn't exploding with 20 call to action buttons.

www.1minus1.com

I love the graphics on this site. A well crafted back-end can be just as important as a pixel-perfect front-end and the illustration of design and development being poured together into a funnel is a great visualization of this.

Fork CMS

When I'm looking to use a new library, gem, or application, I find that the presentation of the product impacts my judgment towards my willingness to give it a try. Fork CMS is a great example of this. There's no reason for me to use a new CMS, but after visiting their website I wanted to download it and try it out anyways.

Dribbbles

Now it's time for a couple of Dribbble shots. This Twitter share shot is particularly awesome for a subtle reason. Twitter makes it very hard to change the style and design of their Tweet button. You can do a custom-designed button that links to Twitter.com, but the user has to leave your website to make the tweet. To allow the user to tweet without leaving your website, you have to use their pre-built button/widget. This person designed around the button, instead of re-designing the button itself, which keeps the best functionality intact while making the developer's job easier.

No explanation needed for this one, I just think it's awesome and would be a really cool login interaction.

I'm not embarrassed to show the inspiration (or exact copy) of my work portfolio design. I was brainstorming the best way to allow users to interact with my professional experience on my website and a colleague of mine sent over this Dribbble. The UI looked so cool that I wanted to code it up just for the fun of it, but I liked it so much that I ended up keeping it.

A lot of these websites were discovered on line25's Websites of the Week series. It's a great RSS feed to follow if you're a fan web design. If you have any websites you would like to share, please link to them below in the comments.

New Additions for your Rails Toolbox

by Dan DeMeyere - @dandemeyere

One of the biggest advantages to using Ruby on Rails as your web framework is the open source community. They unselfishly release new gems every day. They build the best tutorials for free and they commit to the latest Rails builds on a daily basis. The only variable left in the equation when you're building a Rails app is knowing what tools to use when approaching a project implementation. Having a solid toolbox at your disposal is essential to furthering your professional development as it allows you to take on more challenging projects that are outside your comfort zone.

When I first started developing with Rails, I was blown away by my CTO's ability to nonchalantly take on challenging projects. The project or feature would seem outlandish and at times borderline impossible, but he would say something like "we'll figure something out" and somehow he always did. It seemed like magic. After watching closely for many months, I came to realize he had three things: a positive outlook, a solid toolbox, and a creative imagination. The combination of the three were a potent arsenal for tackling epic projects. He wouldn't think about why it couldn't be done - he would start in the ideal world that everything's possible and begin brainstorming from there.

Having a good outlook and creative imagination is not something you can attain from reading a blog post, but you can always add more tools to that handy toolbox. Here are four new additions to my toolbox; hopefully one of these will help you one day when you come across a new project.

Storing your ActiveRecord Objects in Redis

Link to article →

Speed is important. Rails contains a fair amount of overhead and it's considered one of the harder frameworks to scale. It isn't an issue when you're website is small, but as you grow you'll discover some of the earlier code that was written in your app won't hold up as the user base grows. This results in feature re-writes and becoming more clever with your implementation. One of the first tools to reach for when attempting to speed something up (outside of profiling your DB queries) is cacheing. We use memcached at thredUP, but the problem with memcache is that the data isn't persistent. If your memcache server goes down, you can lose all the cached data within it. This makes memcache only feasible for information that can afford to be lost. What about data that needs to be written to the DB? You can't reliably do it with memcache, but you can with Redis.

The tool I linked to above is a gem that the fine folks of Gowalla, recently acquired by Facebook, wrote to accommodate quick writes and reads of an ActiveRecord object. Their example is 'liking' something. You have to be able to like something quickly and pull back information on that like such as how many others have liked it and who they are. Personally I've been wanting to re-write thredUP's in-house notification system for a while as it hits the database on every logged-in page load and this is going to be the first tool I reach for when that time comes.

Converting Dates Between Ruby and JavaScript

Link to article →

This one is very straightforward. In multiple parts of our app, specifically areas of the app we're doing background AJAX polling, our JavaScript scrapes time data off the DOM (like timestamps of objects stored on an attribute of a div). The problem is that JavaScript's time (local) and our server's time (GMT) are in different time zones. The link I listed above will give you a quick and easy way to go back and forth from Ruby's time class to JavaScript time class.

Lazy Evaluation and Method Chaining

Link to article →

Most people know about method chaining in Ruby, especially within the context of ActiveRecord methods. Most people also know that an ActiveRecord call does not hit the database while it's still an ActiveRecord::Relation object, which is an example of lazy evaluation. The real tool comes from using both of these together.

The best example I can give is compound filtering. If you go to an e-commerce website and select 'Sort By: Lowest Price' and 'Gender -> Men', those are options that will compound to filter your results. One way of implementing this is having a nasty 'if params[:sort] = "Lowest Price" && params[:gender] = "Gender"' block for every possible filtering scenario. That is obviously not ideal. But if you were to add some named_scopes that build conditions for each individual filter and method chain all the compounding filters onto a ActiveRecord::Relation object that executes its call to the DB at the end, then that would be a clean way of doing it.

ActiveRecord Key Value Stores

Link to article →

Key value stores are awesome. They're super simple and super fast. To get geeky for a second, searching with key value stores in big O notation have a time of O(1) (that's the fastest). I like to hack together Hash look-up objects in Ruby all the time to speed up checking whether a ActiveRecord ID is in a collection. The alternative is using an array (assuming it can't be looked up in the DB) and even if the array is sorted and the array look-up call is using a simple B-tree algorithm, the notation is still O(log n). You just can't beat key value stores for look-ups.

The link I referenced is leveraging the method_missing method of a class as a way to arbitrarily set key values. I would never use something like this on a heavily used model such as User as using method_missing like that is dangerous, but it does make sense in context of ApplicationSettings. Either way, it's a clever implementation for dynamically setting class attributes and it opens up your imagination for ways in which it can be used.

Have a tool you would like to share? I'd love to hear about it below in the comments.

Facebook FB.ui() apprequests IE Bug

by Dan DeMeyere - @dandemeyere

That title was a mouthful! This post is a simple bug fix for an IE 7/8 issue that I couldn't find any solution for on the interwebs. The bug is as follows: if you use the Facebook JavaScript SDK to send apprequests (the invites that show up in the Facebook notifications jewel) and you're doing so through the FB.ui() method, the default settings will not work in Internet Explorer 7 and 8.

FB.ui() requests use Facebook Dialogs to render the modal. In your FB.ui() call you can reference the way in which you want Facebook Dialogs to render the modal. The options are 'page', 'popup', and 'iframe'. The Facebook documentation states that 'page' is the default, but for FB.ui({method: 'apprequests'}) calls, 'popup' is the default - which looks great in Chrome/FireFox/Safari; however, in IE, the modal never appears. So for IE users you need to set the display method to 'iframe' and it will work fine.

All you have to do is write some simple JavaScript browser detection code to toggle the display method. Here is my CoffeeScript to do this:

In case you're not a CoffeeScript fan, here is the equivalent to the above in JavaScript.

Don't get stuck in development mud

Anyone that has ever done an online startup knows that one of the hardest decisions you continually have to make is where to spend your developer time. The game is a bit of a paradox too because the more you do, the more you have to maintain. This maintenance is "developer mud", and it includes things like, coding new emails, updating old ones, testing alternative views & user flows, improving metrics visibility - the list goes on and on. All these activities are important but the big challenge is deciding when they should take priority over new features.

It's true, a new feature is unlikely to be the game changer it appears to be when it was conceived, but the same can be said for the maintenance. The big difference is how much technical debt you are building up by doing an activity. For example, building a new section of a site for users to communicate on a simple Facebook-like wall might be a great addition for users, but along with that comes the complexity of more schema, more tests, user generated content (an possibly moderation) and other ancillary needs.

One of the places we find ourselves a bit stuck in the mud at thredUP right now is with email. We send a lot of system email and a lot of marketing email. As easy as rails makes email, it is still far too painful. While solving this is not going to reduce the technical debt load, it could take the maintenance side of emails out of developer hands and give our marketers the ability to experiment and test emails freely. My next post will explore a few options out there for us with respect to transactional email.

Rails Association Tips

by Dan DeMeyere - @dandemeyere

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

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:

Free up "inactive" memory on OS X

Have you ever witnessed this?

Why on earth would OS X keep 3.97 GB of inactive memory rather than releasing it?  I think it's to let closed programs launch faster but frankly, I closed the program on purpose so I wish I could turn this off.  While I haven't found a way to turn off this feature, there is a way to circumvent it - pronounced cirsumvent by anyone in the know - and get your RAM back.

Enter "purge".

If you have xcode installed you already have a command-line tool.  Just type "purge" in the command line and voila:

If anyone knows of any problems with this, please reply in comments and let us all know!

CoffeeScript for Beginners (Part 2 of 2)

by Dan DeMeyere - @dandemeyere

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