Hack Friday (Xmas Special)

If you're around Barcelona next Friday the 23rd, we're pleased to invite you to our very special

HackFriday

Our special edition will feature free cake, beers, nougat and champagne and will start at 16:00. We will hack stuff away, discuss about Backbone and other hot trends, CSS 7.0, and basically whatever you want.

Also, if we promised you a Programming Motherfucker T-shirt and you didn't get it yet, this is your chance peoples.

Just comment this post if you plan to come, so we can plan ahead and there's enough beer for everyone :)

Update: Forgot to say where we are!

Comments

DataMapper, an alternative to ActiveRecord

A few days ago we started a new project at Codegram. The project (which is still in development and will be released as open-source soon) is a good challenge for us and a real motivator: we all were tired of using always the same technologies, so we decided to use some tools we hadn't had opportunity to use. One of them is DataMapper.

So what is DataMapper and why using it?

From DataMapper.org:

DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.

From Wikipedia article:

DataMapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.

So, as the Wikipedia article says, DataMapper is an alternative to ActiveRecord. So why using it instead of the default ActiveRecord?

  • No need to write structural migrations
  • Scoped relations
  • Lazy loading on certain attribute types
  • Strategic eager loading
  • Default support for composite and natural keys

As you can see, DataMapper has some really interesting features. This post will be a little introduction to this ORM, let's see some of them.

Using DataMapper with Rails 3.1

First of all, we have to add Datamapper to our Rails project. I haven't found any metagem to include Rails and DataMapper basic gems, so we'll have to use this in our Gemfile:

Gemfile
source :rubygems

gem 'actionmailer'
gem 'actionpack'
gem 'activemodel'
gem 'activeresource'
gem 'activesupport'
gem 'tzinfo'

%w{core constraints migrations transactions timestamps do-adapter rails active_model sqlite-adapter}.each do |dm-gem|
  gem "dm-#{dm-gem}"
end

Our first DataMapper model

No more config needed! What now? Just start coding! Don't forget to bundle install first! Everything right? OK, then, here comes the important part: our first DataMapper model.

A typical DataMapper model (app/models/book.rb)
class Book
  include DataMapper::Resource

  \# Attributes
  property :id, Serial
  property :title, String
  property :synopsis, String
  property :edition, Integer

end

Wow! Amazing! Yeah! Looks beautiful, right? If we check the model line by line, we find that:

  1. The model no longer inherits from ActiveRecord::Base. Oh, wait, we are not using ActiveRecord anymore, so looks legit.
  2. We include the Resource DataMapper module, which adds some basics methods and includes the Assertions module.
  3. We define the id attribute, which will be a Serial. You can find more info about DataMapper data types in the docs.
  4. We define three more attributes: title and synopsis (which are Strings) and edition, which is an Integer.

Now that we have our model written, we have to create the database before creating our first book. Once we enter rake -T on our shell to see all our Rake tasks, we find two new tasks:

  • rake db:automigrate will destroy all our data and update de database to the last version
  • rake db:autoupdate will update our database without destroying our data

So what happens with rake db:migrate? I don't want to lose everything every time I migrate! Don't worry, it's aliased to rake db:autoupgrade, so it won't hurt you if you're too used to rake db:migrate.

We can now create our database with rake db:create db:autoupgrade and we can create our first book in the database! Let's open our beautiful Rails console and create our first book. <spam>I'm using a real world example: a novel written by Patrick Rothfuss which all you fantasy-lovers should read. Oh, and people who just enjoy reading too :)</spam>

:001 > book = Book.create(title: "The Name of the Wind", synopsis: "A rare find these days, fit for lovers of fantasy and newcomers to the genre alike.", edition: 20)
 => #<Book @id=1 @title="The Name of the Wind" @synopsis="A rare find these days, fit for lovers of fantasy and newcomers to the genre alike." @edition=20>

Wohoo! OMG it looks so beautiful! As I know you liked this way of defining the model's attributes, let's take a look at migrations before we go to the controller.

Structural migrations and lazy-loading

Structural migrations? I don't know another way to call them, so I call them this way. Structural migrations are those that change a database table structure: the ones that add or remove a field, add or remove primary keys, change a field type or add or create a table. That is, all the migrations that define the current database structure. Those migrations don't exist with DataMapper.

Let's see the usual procedure with ActiveRecord (actually, the list order is not important):

  1. Think about the model's attributes
  2. Add validations to the model
  3. Write a migration to create the model's table and add attributes

So we often create the migration at the last moment to ensure we don't forget any field. And I repeat, you won't need this last step with DataMapper. Let's take the example from above and suppose we want to modify some model attributes, so our Book model will now look like this:

Our DataMapper model (app/models/book.rb) after some changes
class Book
  include DataMapper::Resource

  \# Attributes
  property :id, Serial
  property :title, String
  property :synopsis, Text
  property :author, String
  property :publication_year, Integer

end

Notice we've added two new attributes, author and publication_year, and we have changed synopsis's type from String to Text. Let's update our database with rake db:migrate and see what has changed:

:001 > Book.first
 => #<Book @id=1 @title="The Name of the Wind" @synopsis=<not loaded> @author=nil @publication_year=nil>
 :002 > Book.first.synopsis
 => "A rare find these days, fit for lovers of fantasy and newcomers to the genre alike."

So what has happened here? the database has been successfully updated to our last version: the book doesn't have any edition number and now has an author and a publication year. And what about the synopsis? What does <not loaded> mean? DataMapper lazy-loads some data types to make database queries faster. This means that fields with a lot of data (like Text attributes) won't be loaded until they are required, like in this example.

Other migrations

What if I really need a migration? Well, that's a good point against DataMapper: this way of migrating and updating the database is really nice, but fails when we really need to change the data. There's a gem out there called dm-migrations which could help you on that, but I haven't tried it, so I can't tell you anything about it right now. Sorry about that :(

Beautiful scoped associations

Let's see another database-related feature from DataMapper: scoped associations. To see the point, we have to add two new models and modify our Book model a little bit:

app/models/author.rb
class Author
  include DataMapper::Resource

  \# Attributes
  property :id, Serial
  property :name, String

  \# Relations
  has n, :books

end
app/models/book.rb
class Book
  include DataMapper::Resource

  \# Attributes
  property :id, Serial
  property :title, String
  property :synopsis, Text
  property :publication_year, Integer

  \# Relations
  belongs_to :author, key: false
  has n, :topics, through: Resource

end
app/models/topic.rb
class Topic
  include DataMapper::Resource

  \# Attributes
  property :id, Serial
  property :name, String

  \# Relations
  has n, :books, through: Resource

end

Woah, not so fast! What does through: Resource mean? Another beautiful DataMapper feature! Stablishing relations through Resource makes DataMapper auto-create the table between books and topics, but that's not all! You want beautiful things? You'll have them. Open your rails console and enter the following after migrating the database:

:001 > book = Book.first
 => #<Book @id=1 @title="The Name of the Wind" @synopsis=<not loaded> @publication_year=nil @author_id=0>
 :002 > book.author = Author.create(name: "Patrick Rothfuss")
 => #<Author @id=2 @name="Patrick Rothfuss">
 :003 > book.topics
 => []
 :004 > book.topics << Topic.create(name: "fantasy")
 => [#<Topic @id=1 @name="fantasy">]
 :005 > book.topics
 => [#<Topic @id=1 @name="fantasy">]
 :006 > book.save
 => true
 :007 > BookTopic.all
 => [#<BookTopic @book_id=1 @topic_id=1>]

WAIT AGAIN! What's that?? Amazing, right? When defining a relation through Resource, DataMapper creates a class so that relation becomes an object! Let's try to destroy this one!

:008 > BookTopic.first.destroy
 => true
 :009 > Book.first.topics
 => []
 :010 > BookTopic.create(book: Book.first, topic: Topic.first)
 => #<BookTopic @book_id=1 @topic_id=1>
 :011 > Book.first.topics
 => [#<Topic @id=1 @name="fantasy">]

So you can play with relations modifying directly the relation object. Let's keep with the scoped associations we were talking about before and try this on our rails console again:

:012 > Author.first.books.topics
 => [#<Topic @id=1 @name="fantasy">]

That's how we get all the topics an author has written about without using dirty Arel Table relations, try this with ActiveRecord ;) Actually, associations are a really powerful resource with DataMapper. We could keep talking about them forever, but you can also take a look at the DataMapper associations docs page, which is pretty neat and clear about that. You can also take a look at the Finding docs page, where you'll find another amazing feature with associations: queries combination.

Rails controllers with DataMapper

Just to end the post, I wanted to show you how a Rails controler looks with Datamapper. I've uploaded a gist with my BooksController so you can have a look at it:

Rails Controllers with DataMapper
\# This class is responsible for the Books REST interface.
\#
class BooksController < ApplicationController

  \# Get a book by the id
  before_filter :get_book, only: [:edit, :update, :show, :destroy]

  \#  Renders the form to create a new Book.
  \#
  def new
    @book = Book.new
  end

  \# Creates a new Book from the params and redirects to edit view.
  \#
  def create
    @book = Book.create(params[:book])
    redirect_to book_path(@book)
  end

  \# Renders the form for a given book. 
  \#
  def edit
  end

  \# Updates a Book from the params and redirects to edit view.
  \#
  def update
    @book.update(params[:book])
    redirect_to edit_book_path(@book)
  end

  \# Renders all books
  \#
  def index
    @books = Book.all
  end

  \# Renders a Book
  \#
  def show
  end

  \# Destroys the Book object from database
  \#
  def destroy
    @book.destroy
    redirect_to action: :index
  end

  private

  def get_book
    @book = Book.get(params[:id])
  end
end

As you see, it's very similar to an ActiveRecord one, except for one thing: DataMapper doesn't have a find method. So use the get method, which works pretty similar to the first one :)

Final thoughts

I must say I love the DataMapper approach about the model, this way of clearly showing what attributes a model has and the clean way DataMapper migrates the database. I've been looking for a good way to have my models information properly sorted and easy to access, and I think I can achieve it with DataMapper and some design pattern like Single Responsibility Principle. I just wanted to introduce you to DataMapper, an ORM not as used as ActiveRecord in Rails world, but I really think you should give it a try.

As a final note, you can find a debate on using DataMapper or ActiveRecord here. You'll find some of the points explained in this post and some more to help you decide :)

Comments

BaRuCo (Barcelona Ruby Conference)

As many of you already know, we attended the RuPy almost two weeks ago. We had such a great time there (if you haven't read yet, here is our codegrammers' guide to the RuPy) that it clicked our minds.

What about we organize a Ruby conference in Barcelona!?

  • Fact: Everyone loves Barcelona
  • Fact: There are a lot of Ruby lovers around the world.

Organize a Ruby conference in Barcelona? Challenge accepted!

BaRuCo

So, here it goes, Barcelona Ruby Conference 2012! a two-day single-track Ruby conference in Barcelona around September 2012 (preferably on of the two-first weekends).

If you think you'd like to come to the BaRuCo, we would really appreciate if you could fill this 6-question survey and help us make a better conference and be sure to follow @BaRuCo2012 for more information and news.

If you're not considering attending but you like the idea, make a difference and spread the word!

Comments

How to achieve more clean, encapsulated, modular step definitions with Spinach

We've been using Cucumber for a while now, and we must say we fell in love with it from the first moment.

But not anymore: It broke our hearts.

You know, we realized what we really loved about Cucumber wasn't Cucumber itself but Gherkin. Gherkin is the feature parser behind it and has some really nice features:

  • A really natural DSL (as natural as it can be)
  • A simple way to abstract a feature description
  • It helps you focus on business value, even if there's no real impact on the actual execution (In order to...)

But what sucks about cucumber?

Step MADNESS

Where exactly should I put my step definitions? What if they're corelated - can I abstract them in a simple way? Can I reuse them across projects? Could I even test them?

With cucumber, you usually run into this kind of situations and there's no easy way to get over it. You should use better step file namings perhaps? Create some methods that live next to each other in the cucumber World? Nah, it just doesn't feel good.

Step ambiguity

Sharing steps between all the features in your project just doesn't scale. It's fine if you have a couple of features, but you start hitting ambiguous steps when it grows off a certain limit.

And when that happens, you must write them taking in account the ones written before, and just having your mind somewhere else misses the whole point of writing them - you should focus on your feature

Regexp-based step matching

Reusable Cucumber steps == ugly steps. If you want a to reuse the same step between multiple situations, either you're going too far in the integration tests (and thus you should be doing that in the unit tests) or you should be writing some helper methods.

It just doesn't feel good not to have explicitly defined what step is being executed. It's like metaprogramming: it can be useful, but most of the times is a bad habit.

So, for that... we made Spinach

Spinach focuses on step reusability and encapsulation so you can reuse them in a clean way across features and projects.

  • Features are just Ruby classes
  • Leverages Gherkin parser
  • Steps are just Ruby methods
  • Supports MiniTest and RSpec as well as Capybara

Fighting step madness and ambiguity

  • Each feature has its own steps (so no more global steps)
  • Explicit reusability through Ruby mixins

Simple architecture

  • Small codebase
  • Fully documented
  • Simple hooks system

Show me an example

Given this feature

Feature: Test how spinach works
  In order to know what the heck is spinach
  As a developer
  I want it to behave in an expected way

  Scenario: Formal greeting
    Given I have an empty array
    And I append my first name and my last name to it
    When I pass it to my super-duper method
    Then the output should contain a formal greeting

  Scenario: Informal greeting
    Given I have an empty array
    And I append only my first name to it
    When I pass it to my super-duper method
    Then the output should contain a casual greeting

This is how its Spinach feature steps file looks

class TestHowSpinachWorks < Spinach::FeatureSteps
  Given 'I have an empty array' do
    @array = Array.new
  end

  And 'I append my first name and my last name to it' do
    @array += ["John", "Doe"]
  end

  When 'I pass it to my super-duper method' do
    @output = capture_output do
      Greeter.greet(@array)
    end
  end

  Then 'the output should contain a formal salutation' do
    @output.must_include "Hello, mr. John Doe"
  end

  And 'I append only my first name to it' do
    @array += ["John"]
  end

  Then 'the output should contain a casual salutation' do
    @output.must_include "Yo, John! Whassup?"
  end

  private

  def capture_output
    out = StreamIO.new
    $stdout = out
    $stderr = out
    yield
    $stdout = STDOUT
    $stderr = STDERR
    out.string
  end
end

Ruby compatibility

Spinach runs on MRI 1.9 and Rubinius/JRuby support is on the works.

Note that not giving support for MRI 1.8.7 is a purposeful choice and not a negligence. This is new software, why should we encourage using legacy versions?

So if you wanna give it a try, here's all you need:

We would really love some feedback. Hope you like it!

Comments

The codegrammers' guide to the RuPy

As you might know, the whole Codegram team have been in Poland for the last week to attend RuPy, a conference aimed to join Ruby and Python communities in a single place. For us, it was also a team building experience where we could get to know each other, think about the direction of our company, ways to improve our workflow and getting some feedback from people there.

So here are our thoughts about our time there:

It’s all about people

Some might think a programming conference can be a boring, formal, cold thing — the fact is that it isn’t at all. Dev people can be very communicative and have a lot of things to say. You can easily take a seat somewhere and just start chatting with anyone — there’s a good chance you will end up learning something.

This time though, organizers were the ones to earn the gold medal. They are caring, warm, commited people who definitely made our stay there a great experience. Thanks Khristian, Kamil, Zaiste, and every single one on the team. We will miss you!

*Khristian was kind enough to take us all for a walk on Thursday morning*

About the talks themselves

RuPy featured some good names: José Valim, Xavier Noria, Yehuda Katz, Obie Fernandez, and some surprises like Fred George, who gave an inspiring talk. We loved all their talks, although some attendants complained that they weren’t “technical enough”. Come on people, there’s so many other things to learn from these guys!

Regarding the Travis talk by Sven Fuchs and Josh Kalderimis, we found it really surprising too. There’s a lot of heavy work behind the scenes! Good job, guys.

Also, we hoped that we could learn some Python, but we barely scratched the skin of the beast when we attended David Beasley’s talk — a very interesting one.

Programming, Motherfucker!

We brought a little surprise with us: a ton of programming motherfucker t-shirts. The deal was that anyone who commited anything to any Open Source project during the days of the conference and tweeted about it gets a free tee. And, oh my, it was a success! People went crazy about it.

*Our moment of glory*

Here’s the summary of all the things that people contributed during the conf (if we missed someone, please let us know):

Those are the motherfucking commiters

We assumed that speakers were already doing a contribution so they got a free shirt too!

So what’s next?

We know it’s early but we’d really want to hear what are the organizers’ ideas for the next RuPy edition. Here’s our thoughts: more Ruby vs. Python stuff, some more hacking time, but keeping the spirit.

Thanks all and see you in the next conf!

Behind the scenes

Comments