Cristian Planas

Ideas of an adventurer developer

The Black Magic of Ruby Metaprogramming

Last Friday I gave another talk at the accelerator Itnig’s offices. After presenting about growth hacking and Facebook, this time I went more technical. I explained one of the most interesting concepts in Ruby: metaprogramming.

Using the story of The Sorcerer’s Apprentice -the one with Mickey Mouse, not the one with Nicholas Cage-, I explain what is metaprogramming, the most common techniques and some of its dangers.

You can also watch the presentation in video:

A Picture With Matz

I met Matz at Baruco!

A picture with Matz at the BaRuCo 2013

By the way, you should watch his keynote. The best moment: “Designing a language means programming programmer’s mind. So I designed a language that programmed you. I brainwash you!” (16:35).

On Startup Metrics

Since I read The Lean Startup for the first time, I have always been interested in metrics. Soon I discovered that developers have a nice advantage over pure marketing guys, as we are able to “cook” our own metrics and also we have a better understanding of how the metrics services as KISSmetrics or Mixpanel work. Actually, I like this topic so much that I started to code a metrics service called DataMorlock: I even bought the domain. Fear me, KISSmetrics!

Anyway, last week I was able to share my experiences on startup metrics in a talk in the Conversion Thursday Barcelona, a monthly event about web analytics and marketing online.

Unluckily, the talk was in Spanish: I hope my next one will be in English. Anyway, enjoy it!

Scaling a Rails Application: Code Tips

Rails is simple. Rails is beautiful. Rails is magical. But when the amount of users starts to grow, it’s time to go back to the basics and refactor your code to improve the performance.

This article is NOT about architecture (you can read a great article about that here. This article is about some very basic tips and tools that all Rails developers should use when trying to improve their application performance. Things like:

  • Caching: Rails provides three different kinds of caching: page, action and fragment caching. Page and action caching do basically the same: cache all the action. The main difference is that action caching gets to the Rails stack and it processes the controller before_filter hooks. This is mandatory if you are using authentication, for example.

Anyway, action and page caching are deprecated in Rails 4. The real thing here is fragment caching: to cache any part of a process, including part of view rendering. This is specially useful in expensive calculations that don’t change in a long time, like periodical statistics. In Playfulbet, I cache using memcached and dalli.

For a better understanding of Rails caching, I would recommend to read the episode Obie Fernandez wrote about it in The Rails 3 Way. Rails documentation is fine, too.

  • Eager loading: Eager loading is a way to fetch all the associated objects with a single DB query.

An example:

user.bets.map { |bet| bet.option.odds }

This code will result in 1 + n calls to the DB, where n is the number of bets that the user has.

user.bets.includes(:option).map { |bet| bet.option.odds }

This code will result in 2 calls to the DB.

You also can include a deep hierarchy of associations using a hash: user.bets.includes(:option => {:market => :event}). Eager loading also accepts a :conditions option.

There is another issue with eager loading: that it is not lazy. That means that the query will get executed in the controller, not in the view: and that could lead to unnecessary queries (for example, if part of the view is cached).

You can learn more about it in this Railscast episode.

  • Materialize: If you need to materialize attributes, just do it. As a rule of thumb, accessing the DB is “cheaper” than processing in Ruby (it’s a general rule, there are plenty of exceptions). Reading an attribute is better than calling a method that calculates it. Pretty obvious, no?

The “materialize” rule has another meaning: to avoid recurring queries materializing the value in a column. A basic example of this philosophy is counter-cache, a DB column automatically updated by Rails that saves the total amount of a multiple association. Like this, it completely removes the burden of a recurring SELECT COUNT(*).

There is a third meaning: to materialize in a model an attribute of another model that the former is using recurringly. You need to be EXTRA cautious about that -somehow it’s a violation of basic OOP principles- and only use it when it will make a big difference in performance. For example, when there are many classes between the accessor and the accessed.

  • Use pluck: If you are using queries that return a large amount of records, that’s a big burden for your server’s memory. That’s specially not optimal if you only need a single column of the record.

pluck, a method added to Rails in 3.2, solves that problem. Essentially, it selects a single column in your SQL query. I will give you a real example from Playfulbet code. In the first case, we make a Bet query loading thousands of User objects, which are quite heavy:

user_ids = User.where("created_at < ?", Time.now.beginning_of_month).map(&:id)
Bet.where(:user_id => user_ids)

On the other hand, this loads only an array of integers for making the same query:

user_ids = User.where("created_at < ?", Time.now.beginning_of_month).pluck(:id)
Bet.where(:user_id => user_ids)
  • Learn how your 3rd party code works: In this case, prevention is better than cure: choose very carefully your gems. Go for those who have a full test suite and GitHub activity. And even those have to be learnt, as the use you are doing of them can be optimized for your own purposes.

A simple example: the very popular will_paginate performs a SELECT COUNT query to calculate the number of pages. This query can be avoided if you materialize its result and pass it directly to the paginate method in the :total_entries option. In this case, I paginate the bets of a user without querying the total amount and using counter-cache:

@bets = @user.bets.paginate(:page => params[:page], :total_entries => @user.bets_count)

Playfulbet Wins an Investment Forum

Some weeks ago, my partner and me made a pitch at one of the most important investment forums in Spain, the First Tuesday. In it, we presented Playfulbet to Business Angels and Venture Capital Funds. And it looks like that they liked our project, as the assistants chose us as the best project presented.

Pol and me presenting Playfulbet

Even if this victory doesn’t imply any investment, it obviously shows the potential of Playfulbet. We thank all the First Tuesday attendants for trusting us.

You can read more about it here (in Spanish).

On Slideshare Homepage

In my last post, I showed you One Graph to rule the all, the presentation I made at Itnig’s Fridays (a popular event in the start-up scene in Barcelona).

This same presentation brought me a nice surprise today. It was featured in Slideshare homepage:

Pol and me presenting Playfulbet Sorry, I couldn’t take any screenshot of the actual Slideshare homepage.

Mine was the first Itnig’s Fridays presentation featured in this popular site homepage. I hope this helps to extend the use of Open Graph!

One Graph to Rule Them All

In Playfulbet, we decided to use all the tools available to make ourselves viral since day one. And very soon we discovered that Facebook Open Graph was extremely valuable. Right now, this is giving us around 600.000 prints and 5.000 clicks every month, totally for free. Also, given that the prints are triggered by users’ actions, those numbers will increase with more users. So more users bring more Graph actions and more Graph actions bring more users. It’s a snowball effect: pure virality.

To explain this, and much more, I made the presentation One Graph to rule them all: Integrating your application with Facebook at Itnig’s Fridays. In the presentation, I described all the process that a developer must follow to publish its application’s actions in the Open Graph: asking the right permission from the user, creating a page for every object that will be used in the actions and, finally, defining the action itself. I also talked about the most typical issues: the weird behaviour of Facebook’s cache and the unpredictable response of Facebook staff when they have to approve your action. I finished the presentation remarking what a great difference can this make in your application visibility.

Usually all the Itnig’s Fridays talks are recorded, but this was lost because of some weird technical error. Anyway, if you have any doubts about the presentation or the Open Graph, you can tweet me at @crplanas.

Playfulbet

Last month, after seven happy months working at Itnig, I started a new professional challenge: from now, I am the CTO of Playfulbet.

Until now, I was Senior Ruby developer and Project Manager at Itnig: a start-up accelerator. There I worked as developer in projects like PharmaDating or the Instituto Maxilofacial website. But my main task was being the project manager (and lead developer) of Playfulbet. And I liked the project so much that I decided to dedicate myself entirely to it.

Playfulbet logo

So a big nominal change (from Ruby developer in one company to CTO in another), but smaller in fact: I am still the man behind Playfulbet. Maybe the real change is philosophical. Before I was a developer who happened to like the start-up environment; now I am also risking myself as an entrepreneur.

Playfulbet homepage

┬┐And why did I decide to risk myself? First of all, I think that Playfulbet is an extremely cool project with a bright future ahead. Playfulbet is a sports betting social game, a project that puts together two areas which are greatly growing: social gaming and gambling. Also it has some of the elements that attract me more to a project: big data (bets and users data) and a social aspect.

Wish me luck!