Ditch Google’s Blasé Favicon Service, Grabicon Loves You

In high school, I was infatuated with a girl named Virginia. Her curly hair and perky nose gave her a Marilyn Monroe quality that blinded me to the worst thing about her…she just wasn’t that into me.

Eventually, I found the cure. I wish I could say it was self-respect, but the real trick was to find a great girl who actually liked me back!

Google’s Favicon API Just Isn’t That Into You

The biggest problem with Google’s favicon service is that Google never really wanted you to use it in the first place. They created it as an internal tool for their ad networks and such, but some enterprising developers dug through Google’s JavaScript and found the hidden links.

As it turns out, this makes ALL the difference, and it shows in multiple ways:

  • Favicons are only 16 pixels, even when larger sizes are available.
  • Missing favicons result in a very unassuming grey globe.
  • Google can lock down the service any time it wishes.

In these ways, Google is a lot like Virginia:

  • We only did things she wanted to do.
  • Most of my calls went unanswered.
  • Eventually she wasn’t even interested in hanging out as friends.

All of this is because Google’s favicon service was designed for only one customer: Google. And you can’t blame them any more than I can blame Virginia.

I Know Someone Who Likes You!

You need to replace Google’s unsupported, unintentionally public favicon service with something great that loves you back. That something is Grabicon.com. How does Grabicon solve the Google favicon problem?

  • Request icons in the size you want, and you will get them in that size, every time, even when the original site doesn’t provide that size icon. Grabicon “makes it right” by resizing the image in an attractive way.
  • You will always get a unique icon back from Grabicon, even if the original site doesn’t have an icon at all. It will generate a stand-in, so you can use it in your interfaces with confidence.
  • Grabicon doesn’t just like you back, its whole point in existing is for YOU. It’s not going anywhere.

Again, this makes all the difference! You can use Grabicon mobile/web apps and know that it’s giving you more than Google would, and it’s a long-term solution.

How Does it Work?

Grabicon is free for basic usage, and was designed to be a drop-in replacement for Google’s favicon service. Instead of doing this:

http://google.com/s2/favicons?domain=rubycuts.com

You do this:

http://grabicon.com/icon?domain=rubycuts.com

By default, Grabicon will give you 32 pixel icons instead of Google’s 16 pixels, but if you’re really into squinting, just ask for the smaller size:

http://grabicon.com/icon?domain=rubycuts.com&size=16

Since icons are always square, you don’t need to specify height and width separately. Sorry if you were looking for lengthier parameter lists, but that’s really all there is to using Grabicon. It’s a dead-simple, no-brainer Google replacement.

How Does it Look?

It looks awesome. Gemerald.com uses Grabicon, and here’s the difference:

Google Favicons vs Grabicon on Gemerald.com

Google Favicons vs Grabicon on Gemerald.com

I literally swapped out favicon urls using Chrome’s developer tools to make the Google version, so this is as apples-to-apples as it gets. At 32 pixels, there’s no comparison. And you can argue that Google’s icons would definitely look better at their native 16 pixel size, but why would you want that??

Can’t I Build Something Myself?

You can, but again, why? Grabicon is free, and does the hard work for you. Favicons can take 4-6 seconds of redirects and page loads to ferret out, since there are a handful of ways a site can implement them. Grabicon caches results so all users get the benefit of instant icons.

If it sounds like I have an unhealthy love of Grabicon, it’s because I do. It’s my baby. I created it as the first endpoint of a much larger endeavor – making brand integration dead-simple for mobile and web applications. And this endpoint will always be free for basic use. I’m also excited to see Grabicon pop up in apps where Google was never used because it just wasn’t up to the task.

Please try it, and tell me what you think. I hope you’ll be impressed, but I’m always open to hearing about ways to make it better. Enjoy!

Become a Code Ninja with Codewars

I am not a ninja, in the traditional sense. My chubby frame and fuzzy beard can attest to that. But Codewars has given me the ability to be a ninja in one very special area of my life: programming.

Kata are moves that one practices and perfects as they attempt to master a martial art. In this spirit, Codewars presents you with hundreds of kata (coding challenges) in the programming language of your choice. As you earn honor points for completing kata, you advance through the “kyu” (ranks).

The concept of programming kata has been around in other forms, but Codewars is an entire platform of crowd-sourced programming challenges. Users are encouraged to create kata of their own that are curated and used by others. It’s a self-perpetuating system (with a lot of hard work from the Codewars staff).

Each kata has a description, a browser-based code editor, and even a small testing library you can use to verify your own solutions. Once you’re confident you’ve solved the kata, you can submit your code to see if it passes the kata author’s own set of tests. Instant gratification!

kata

Why Train?

As I said earlier, programming kata is not a new concept. Years ago, Chad Fowler published a book that stressed the importance of practicing your programming craft. Chad posed an interesting question: you wouldn’t expect to become a great musician with all performance and no practice, so why do we think we can become great developers without challenging ourselves outside of work?

Malcolm Gladwell explored the concept of “10,000 hours” in his book Outliers. The theory is that it takes about 10,000 hours of dedicated practice to become an expert at something. If you’re like most developers, 90% of what you do at work doesn’t count.

Becoming an expert requires constant challenge, and that’s what Codewars provides. They gamify the act of self-improvement, and they do it well – it’s downright addictive!

 

 

Programming Kata: Treat a Hash Like a JavaScript Object

In JavaScript, objects look and act an awful lot like hashes:

var hash = {a: 'b', c: 'd'}

hash.a  #=> 'b'
hash['c']  #=> 'd'

How can we mimic this in Ruby? It’s easier than you might think. Ruby classes have an instance method called `method_missing` that is called whenever…you guessed it…it can’t find the method you asked for. Since Ruby allows us to open up any class and extend it, let’s do that now:

class Hash
  def method_missing method_name, *args, &block
    return self[method_name] if has_key?(method_name)
    return self[$1.to_sym] = args[0] if method_name.to_s =~ /^(.*)=$/
    
    super
  end
end

Now we have JavaScript object-like power in Ruby hashes:

hash = {:five => 5, :ten => 10}
hash.five  #=> 5
    
hash.fifteen = 15
hash[:fifteen]  #=> 15

We’re doing three things here. First, we’re checking if the hash has a key by the given method name (as a symbol). If it does, we return the value. Next, if method_name ends in an equal sign, we create a new hash entry with the value specified. Finally, it’s very important to always call `super` at the end of `method_missing`. This way, if the method is still missing, other parents classes up the inheritance chain might provide the solution.

You can practice this as an interactive kata on Codewars.

Rubyists Should Learn from Ford’s Example

From the moment I laid my twelve year old eyes on the Ford Mustang, I was in love. But even before that, I remember taking road trips to Wisconsin, bouncing around in the covered bed of my dad’s F-150 pickup with my sister. Back then, we didn’t wear seat belts – my parents would lay down a mattress for us to play on in the back, while they enjoyed the eight-hour journey in relative peace and quiet up front.

I’ve been a Ford guy all my life. But in the 90’s, a disturbing trend began. Ford, and indeed most auto makers, started homogenizing their product lines.  As the “curvy design” fad erupted, Mustangs were redesigned to look more like the Taurus. And F-150’s were redesigned to look more like…the Taurus. I hope they saved a lot of money on design work, because everything had the same oval headlights and curved hood. Each model was trying to be everything to everyone.

Just when all looked lost, Ford came to its senses in the 2000’s. They started designing the cars so people actually knew what they were for. The mustang now looks like a muscle car:

mustangs

The Fusion, which evolved from the Mercury Milan, now looks sporty, but efficient:

mid-sedans

The Five-Hundred (which looks better in person) boasted size, style, and luxury:

full-sedans

And finally, the F-150 now looks like the workhorse it was meant to be:

trucks

Rubyists Can Learn from Ford

First, show intent. While code comments can be helpful, they can also be a crutch. Ruby is a wonderfully expressive language, so use it. Spend time naming your classes, modules, methods, and variables with the intent of having them be perfectly understandable to a stranger. When a method has several parameters, wrap them in a hash so developers (yourself included) can better understand what a method call is trying to accomplish. As a bonus, you won’t have to look up the parameter order every time you want to use the method.

Keep your methods small, and remember the old mantra: a method should do one thing, and do it well. But don’t stop there. Controllers shouldn’t be stuffed with dozens of actions; you probably need more controllers that each handle a more specific part of your application.

On a larger scale, don’t limit yourself to just one app. If your company or project is doing lots of different things, it may need several different apps. They can still talk to the same databases when they need to, and they can appear seamless to a site visitor.

Businesses Can Learn from Ford

A lot of businesses also make the mistake of trying to be everything to everyone. I see this a lot with consulting companies in my own industry. In order to cast the widest net, dev shops will take on any type of work, that uses any programming language or technology they have experience with. Sometimes they might not even have that experience, and that’s usually good news for me. Rescue projects are a big part of my business.

I’ve chosen to focus on the Ruby programming language, and I put my money where my mouth is when I chose my business name. That doesn’t mean I stop learning other technologies. It means that I choose to invest my limited time learning the technologies that will make me a better Ruby developer. Currently I’m digging into PostgreSQL, because it has so much more power than just database queries, and this will improve the performance of my Ruby applications. I also have several years of Perl experience, but I choose not to take on Perl contracts.

RubyCuts is relatively new. During the toddler stage, I’m more open to taking on lots of different types of projects. As we grow, we will focus more and more on our core – training, scaling, and rescue. Lots of developers can build basic applications in Ruby, but I want RubyCuts to be the Navy Seals of the Ruby world. I want to help companies solve the toughest problems so their dev team can get back to building money-making features. I want to make it as easy as possible for companies to invest in Ruby.

I think the future of small business is in specialization, solving very specific problems. The trick will be picking the highest value problems to solve. As Ruby gains popularity, I think the increased number of beginners will require an increase in experts. If I’m not successful in five years, you have my full permission to rub this article in my face 🙂

 

 

All I Need to Know about Business, I Learned on StackOverflow

I recently ran across this light-hearted post on StackOverflow. If you’re not familiar with StackOverflow, it’s a question/answer site for programmers. Users gain reputation points for answering questions from other users, and it can be addictive to grow your reputation over time. I’m in the top 3% of StackOverflow users, myself.

Based on the principal that 10% of the world’s population owns 90% of the wealth, one user wanted to see  how much of the total reputation points were “owned” by the top 10% of users. His initial calculations showed that 95% of all reputation points belonged to this group! It wasn’t long before people started cracking jokes about our economy:

stack overflow reputation comment

and:

stackoverflow reputation answer

Of course, the national/global economy and the StackOverflow economy are two very different things, and I’m not trying to trivialize some very tough problems the U.S. faces. But there’s still a nugget of wisdom here. While reputation points do offer some benefits on the site, they are not “spent”, per se. So your reputation is really a measure of the value you’ve generated.

If you apply this principle to your business endeavors, you might be amazed at how well it works. As a contract Ruby developer over the last seven years, I’ve learned that my success is closely tied to the value I generate for others. I’m not just talking about doing a good job for my clients, though that comes first. I do a lot of things I don’t get paid for, directly:

  • I speak at local Ruby events.
  • I’ve co-organized both the Kansas City and Lincoln, NE ruby meetups.
  • I answer a lot of Ruby questions on Stack Overflow.
  • I’ve contributed to open source projects, including Ruby on Rails itself.
  • When I don’t have the availability to take on new clients, I refer them to other good developers I know.

These things have been very rewarding on their own, but have they “paid off” in real dollars? Absolutely. Fellow Rubyists refer work to me, because I have a good reputation.  One client skipped the first half of their interview process entirely, based on my contributions to Rails. And yes, being a “3-percenter” on StackOverflow has given clients the confidence to trust my expertise.

My advice to any up-and-coming developers is always the same: look for ways to generate value, whether they pay directly or not. If you’re a contractor, you’ll benefit in many of the same ways I do. If you’re a recent college grad, your open source contributions and public speaking will say more about your ambition and talent than your GPA.

In fact, generating value should be the top priority of every business. That’s why the best mission statements tell people what value you provide, not what things you sell. We all like dollars. What sets you apart in business is how valuable you are to the world.

Enumerable Magic – Introduction

Whether you realize it or not, you get a lot of use out of Ruby's Enumerable module. It shows up in arrays, hashes, file I/O, database interactions, and more. I'm going to explain what this module is, and how you can put it to use in your own Ruby classes.

What is a Module, and what is the Enumerable Module Specifically?

In Ruby, a module is a collection of methods, constants, and variables that can be included in classes to extend their functionality. The Enumerable module is responsible for a lot of the power behind arrays and hashes. If you've ever used methods like map, select, or count on an array, you weren't using methods built into the Array class itself - they were mixed in from Enumerable!

Here is the simplest version of a class which includes the Enumerable module:

class List
  include Enumerable

  def initialize
    @items = []
  end

  def each
    @items.each{|item| yield item}
  end
end

We start by including the Enumerable method. Then we provide an each method which all the Enumerable methods will use to iterate over the items in our list. While this example uses an each within an each, you don't have to. We can accomplish the same thing with successive yield calls in our each method. You can see this in an abbreviated version of the PetInventory class included with this lesson's source code:

# full source: https://github.com/rubycuts/enumerables/blob/master/lib/pet_inventory.rb

class PetInventory
  include Enumerable
  
  def initialize
    @dogs = Pet.new('dog', 4, 100)
    @cats = Pet.new('cat', 4, 50)
    @fish = Pet.new('fish', 0, 1000)
  end
  
  def each
    yield @dogs
    yield @cats
    yield @fish
  end
end

Calling yield three times in our each method means that any Enumerable methods will treat our PetInventory object as a collection with three items - a dog, a cat, and a fish.

This example also illustrates another good point. We were sort of cheating in our first example. Since @items is an array, it already has the enumerable methods available - no need to wrap it in the List class. In real life, almost every time you have a collection class, it's going to be a container for a groups of another class you've created. In this case, PetInventory is managing a collection of Pet objects.

Using Enumerable Methods

One of the easiest Enumerable methods to understand is sort_by. It will sort an enumerable collection based on the formula you give it. We'll use this method to illustrate the two main ways you will call most Enumerable methods. First, the long way:

pets = ['rooster', 'dog', 'fish']

# sort by pet name length
pets.sort_by{|pet| pet.length}  #=> ['dog', 'fish', 'rooster']

# sort by third letter in name
pets.sort_by{|pet| pet[2]}      #=> ['dog', 'rooster', 'fish']

We pass sort_by a block that will be run on each item in the list, and the list will be sorted based on the outcome. When the block will call a simple method on the object, as in the case of pet.length, there is a shorthand way to write this:

pets.sort_by(&:length)

This only works with simple methods that require no arguments, but you'd be surprised how often this is the case. Notice we couldn't sort by third letter using this shortcut, because that's a more complicated formula.

What Else?

Learning the Enumerable module will give you merlin-level powers over simple Hashes and Arrays, but learning to use Enumerable in your own classes will make you...whatever level wizard is three slots above merlin.

At first you might be hard pressed to think of places to use it, but it shows up more than you think. Ruby's File class allows you to iterate over each line in a file as if it was an Array, thanks to Enumerable. Many database wrappers do the same for select queries. In my example code, I flesh out a basic LogData class that iterates through Heroku logs so you can work with them without needing to load the entire log file into memory at once.

Like any great tool, once you start looking, you'll find more uses. I've just given you a hammer, and there's a world full of nails out there. Enjoy!

Automatic Summary Tables in PostgreSQL

Has your app begun to slow down over time, whether you're seeing a large increase in traffic or not? It might be that those complex database queries that were snappy when you first launched are now taking longer and longer to execute. The first step is proper indexing, but you likely did this when you created your tables. It might be time for summary tables!

What are Summary Tables?

Summary tables are a simplified view of your complicated data that can be queried more quickly and easily. Are they magic? Absolutely, but not how you might think. Real-life magic requires a real-life magician pulling strings behind the scenes, and that's what you'll have to do. You will setup the trick, and your app's users will enjoy the show. But with just a little extra knowledge, you can be magic and lazy at the same time.

The Process

The trick follows this formula:

  • Create a table with the summary data as you'd like to see it.
  • Build a stored procedure that updates the summary table.
  • Setup a trigger that will run when your original tables are updated.

We're going to begin with a simple data model: a table for species of animals, including how many legs each species has, and a table for pets, who belong to a specific species. We want to easily query the database for the number of pets who have, say, four legs. Here's the structure for our animal tables, minus any keys:

CREATE TABLE species (
    id integer NOT NULL,
    name text,
    leg_count integer
);

CREATE TABLE pets (
    id integer NOT NULL,
    name text,
    species_id integer
);

And here's the query that gives us a tally of how many pets have each number of legs:

SELECT species.leg_count as leg_count, count(*) as pet_count
FROM pets
JOIN species on pets.species_id = species.id
GROUP BY species.leg_count

Now, to the magic.

Create the Summary Table

Our summary table is easy; it has the same format as the output of our complex join query:

CREATE TABLE leg_counts (
    id integer NOT NULL,
    leg_count integer,
    pet_count integer
);

Each record stores a leg count, and the number of pets that have that many legs.

Build the Summary Table

Here's the code:

CREATE FUNCTION update_leg_counts() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
    DECLARE
     pet_leg_count INTEGER;
     pet_count INTEGER;
    BEGIN
      SELECT INTO pet_leg_count species.leg_count
        FROM species
        WHERE species.id = NEW.species_id;
    
      SELECT INTO pet_count count(*)
        FROM pets
        JOIN species ON species.id = pets.species_id
        WHERE species.leg_count = pet_leg_count;
    
      DELETE FROM leg_counts where leg_counts.leg_count = pet_leg_count;
      INSERT INTO leg_counts (leg_count, pet_count) values (pet_leg_count, pet_count);
  
      RETURN NULL;
    END;
    $$;

Now that's a mouthful! We start by creating the function, with a return type of "trigger". This particular stored procedure has no parameters - it will be triggered by the creation of a new "pets" record, and that new record will be available within the function as "NEW". We set the language of the stored procedure as plpgsql, and declare a couple of variables that will be used in our code.

We set pet_leg_count to the number of legs that our new pet has. This is important, because we don't want to update ALL the records in our summary table, just the one that keeps track of our pet's same-legged friends. Next, we set pet_count to the number of pets with this many legs. Finally, we delete any summary table records with the same number of legs, and recreate it with the new leg count. We do it this way so our code works whether a record for that many legs previously existed, or not.

Setup the Trigger

Now for probably the easiest part of this process: telling Postgres to execute the stored procedure whenever a new pet is added:

    CREATE TRIGGER update_leg_counts
    AFTER INSERT ON pets
    FOR EACH ROW EXECUTE PROCEDURE update_leg_counts();

I gave the trigger the same name as the stored procedure, sorry if that's confusing. I didn't see a good reason to give them distinct names.

The Results

The difference is...magic? As we add pet records, we can measure the speed of querying pet counts by number of legs, both before and after the summary table. These were my actual performance numbers, which you can recreate with the code in the git repository I provided at the top of this article.

Number of Pets Query Time w/o Summary Query Time with summary Speed Improvement
100 0.0006 0.0002 65.98%
500 0.0007 0.0002 71.71%
1,000 0.0013 0.0002 79.86%
2,000 0.0019 0.0002 88.52%
3,000 0.0026 0.0002 91.04%
4,000 0.0033 0.0002 92.66%
5,000 0.0040 0.0002 93.41%
6,000 0.0049 0.0002 94.91%
7,000 0.0055 0.0002 95.77%
8,000 0.0062 0.0002 96.34%
9,000 0.0069 0.0002 96.46%
10,000 0.0094 0.0002 97.12%

The speed of querying the summary table remains constant no matter how many pet records we add to the database, while performing the complex join query gets increasingly sluggish. Even at just a hundred pet records, there is marked benefit. By the time we're storing 10,000 pets, we're saving over 97% of the time it takes to find out how many same-legged friends Fido has. Magic!