Simone Web Design

Getting Started With Rbenv

| Comments

If you are struggling to get rbenv working on your machine, then I believe you landed in the right place: here I’m sharing some gotchas I had while setting up rbenv on Mac OS X 10.9.3.

First of all, make sure you remove RVM completely. It’s not compatible with rbenv.

$ rm -r ~/.rvm

Remove it from your $PATH as well.

I’m using fish shell, that has its own quirks, such as it doesn’t have a export command to export variables to $PATH. Instead it uses set. E.g.:

$ set VARIABLE VALUE

For example, in order to call rbenv, I set up my $PATH this way:

$ set -u fish_user_paths $fish_user_paths ~/.rbenv/bin

Fish also handles things a bit differently. If you are using it, you’ll probably be burned by the fact it doesn’t understand the $ function that in POSIX shells creates a sub shell. Fortunately I managed to find a fix for that: see this article. Basically it says you need to add this code to your config.fish file:

set -gx RBENV_ROOT /usr/local/var/rbenv
. (rbenv init -|psub)

But pay attention and make sure you understand what’s going on here. Actually the code above didn’t work for me, as the installation path of my rbenv was different. If you installed rbenv with git clone, the right code is:

set -gx RBENV_ROOT ~/.rbenv
. (rbenv init -|psub)

In fish it’s also possible (albeit not recommended) to use the config.fish file in order to set the $PATH variable permanently. You can do it with (e.g.):

set -x PATH ~/.rbenv/shims /usr/local/bin /usr/bin /bin /usr/sbin /sbin $PATH

A big gotcha here is to have ~/.rbenv/shims before /bin and /usr/bin, otherwise the shell will load the system’s Ruby first (and you don’t want to use the system’s Ruby for your projects).

To ensure I was using the right Ruby version, I moved the system Ruby away, in /tmp. Of course you need to sudo for that:

$ sudo mv /usr/bin/ruby /tmp

Another super important thing is: NEVER EVER install gems using sudo. If you do that you’re going to have serious problems/conflicts and weird errors in your shell. Do yourself a favour by installing things in your home (~) and avoiding sudo at all costs. Always.

A good thing to do for ensuring you are going down the right path is to use which: which rbenv, which ruby and which gem will tell you if you actually have your stuff in the right place (that is the .rbenv/shims on your home folder).

At this stage you may be able to install Ruby (you need the ruby-build plugin for that). Run:

$ rbenv install -l

The command above will give you a list of all the available rubies to install. Run, for example:

$ rbenv install 2.1.2
$ rbenv rehash

The above will install Ruby 2.1.2 into ~/.rbenv/versions and will rebuild your shim files. Note that you need to run rbenv rehash every time after you install a version of Ruby.

Another useful command is:

$ rbenv global

This tells you which version of Ruby you have. It may differ from what ruby -v says to you, and if that’s your case, you’ll probably want to check your $PATH.

Hopefully that’s enough for getting you started with rbenv. Enjoy!

Bye Bye Wordpress. Welcome Octopress!

| Comments

Octopress

I did it! I’ve finally migrated my blog to Octopress. It was a bit of a PITA, and it took a lot more than what I expected, but I did it.

Apologies if you weren’t able to see the website yesterday; the DNS took about 11 hours to propagate, and the site was back UP just this morning. It is now hosted by Heroku and it’s faster than ever.

Prepare yourself to see lots of new stuff in the next few weeks! ;-)

Ruby Is Magic

| Comments

Have you ever heard about Ruby? It’s my favourite programming language. It was invented in Japan, which is probably the most amazing country in the world, and I think no language can beat Ruby when it comes to magic. Yes: Ruby is Magic.

You don’t believe me, do you? Fair enough, but let me show you why Ruby is so awesome.

You can read and write it like English.

Yes, it’s true. Ruby is so simple and intuitive that you can think in English before writing some Ruby code. For example:

1
2
3
def speak_english
  print "Hello, world!"
end

The code above is a Ruby function (or method) declaration. So, when you want to run the speak_english function, you do it this way:

1
2
speak_english
Hello, world! => nil

You may have noticed the nil: what’s that? It’s just nothing, literally. It represents the void (emptiness, no value at all). In other languages, such as SQL (the mother tongue of databases), you can find it as NULL.

In Ruby, everything is an object.

Do you know about OOP? It means Object-Oriented Programming, and it’s probably the most important programming paradigm ever invented so far. Ruby takes full advantage of OOP. And when I say full, I literally mean: everything, in Ruby, is an object. Even numbers! If you know at least one programming language, say Java, you must be aware of the fact that Java numbers are primitive types, which mean that they’re not objects. In Ruby, things are different.

Let’s make an example. Let’s say you want to use the speak_english function 3 times. In Java, you’d do something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HelloWorld
{
    public static void main(String[] args)
    {
        for (int i = 0; i < 3; i++)
        {
            speakEnglish();
        }
    }

    public static void speakEnglish()
    {
        System.out.println("Hello, world!");
    }
}

So much code for something so simple… in Ruby, instead, you can do this:

1
2
3
4
3.times do
  speak_english
end
Hello, world! Hello, world! Hello, world! => 3

See? I called a function on a number! Cool, isn’t it? And I used only 3 lines of code :-)

Ruby is clear, concise and understandable.

I was a PHP developer when I discovered Ruby. Although I had a bit of OOP background, I was used to write PHP code in a procedural style. Procedural code looks something like:

1
2
3
doThis();
doThat();
doSomethingElse();

There’s absolutely nothing wrong with this approach, apart from the fact that it starts being cumbersome, sometimes… because it’s not Object-Oriented. I’ll make one last example, taken from a beautiful StackOverflow’s answer.

Reverse the words in this string:

backwards is sentence This

So the final result must be:

This sentence is backwards

When you think about how you would do it, you’d do the following:

  • Split the sentence up into words
  • Reverse the words
  • Re-join the words back into a string

In PHP, you’d do this:

1
2
3
4
$sentence = "backwards is sentence This";
$splitted = explode(" ", $sentence);
$reversed = array_reverse($splitted);
$rejoined = implode(" ", $reversed);

In Python:

1
2
3
4
sentence = "backwards is sentence This"
splitted = sentence.split()
reversed = reversed(splitted)
rejoined = " ".join(reversed);

And Ruby:

1
2
3
4
sentence = "backwards is sentence This"
splitted = sentence.split
reversed = splitted.reverse
rejoined = reversed.join

Every language required 4 lines of code. Now let’s compare the one-liners.

PHP

1
implode(" ", array_reverse(explode(" ", $sentence)));

Python

1
" ".join(reversed(sentence.split()))

Ruby

1
sentence.split.reverse.join " "

Now, can you see the beautiness of Ruby? It’s just… Magic.

I love Ruby.

Bash Script for Batch Running OptiPNG

| Comments

Optimize all your images with a single command:

$ find . -name '*.png' | xargs optipng -nc -nb -o7 -full

What is OptiPNG?

OptiPNG is a PNG optimizer tool. If you want your website to be faster, you should consider optimizing images.

When I ran the Google PageSpeed tool towards my website, I got a score of 81/100 for Desktop, 61/100 for Mobile. Pretty low, I thought. So I decided to go through the “Consider Fixing” issues, and the first one was - guess what? - optimize images.

Properly formatting and compressing images can save many bytes of data.

OPTIMIZE ALL THE IMAGES!The thing I did immediately next was reading the article that Google suggested: it’s a nice reading on Google Developers about optimizing images. The first recommendation is: Use an image compressor. OptiPNG is one of them.

On the OptiPNG site I realized it works only for one image at a time, so I had the need to write a script that runs the optimizer for all images at the same time.

Luckily enough, after a bit of search, I found a blog post titled Optimize all PNG images recursively, which finally solved my problem. All the credits belong to that blog.

After running the script I got a score of 86/100 for Desktop (before was 81), and 68/100 for Mobile (before was 61), all without loss of quality. Definitely worth a try!

Rails 4: Update/synchronize Views With Database Schema After a Migration

| Comments

So you just updated your model and the related database schema, but your views are now obsolete. How to refresh them?

Well, there are a lot of premises to say here. First, there’s no actual way to synchronize your views with your model. The best way is to do it manually, but it’s not the only way. The other way, which I’m going to explain in this post, actually only works if you are willing to scaffold your whole model/view/controller/tests from scratch. This is probably not desirable in most of cases, but I assure you can safely try this path if you are in a early stage of development, or if you are ok with the default (generated) Rails’ views. So, whatever, if you don’t want to rake generate scaffold your_resource again, you can stop reading now.


Oh well, you are still reading :-)

I’ll proceed explaining how to synchronize your views after the migration(s) you have run. Let’s just start from scratch.

A full example

Let’s say we have these two models: Child and Toy.

Child
  • name
  • birth_date
Toy
  • description
  • price
  • child_id

As you might have already guessed, I am going to tie our models with a one-to-many relationship: a child has_many toys, and a toy belongs_to a child.

app/models/child.rb
1
2
3
class Child > ActiveRecord::Base
  has_many :toys
end
app/models/toy.rb
1
2
3
class Toy > ActiveRecord::Base
  belongs_to :child
end

Let’s create the application and scaffold these resources:

1
$ rails new DemoApp && cd DemoApp
1
2
3
$ rails generate scaffold child name birth_date:date

$ rails generate scaffold toy description price:decimal child:references

Run the migrations:

1
2
3
4
5
6
7
8
9
10
$ rake db:migrate
==  CreateChildren: migrating =================================================
-- create_table(:children)
   -> 0.0014s
==  CreateChildren: migrated (0.0015s) ========================================

==  CreateToys: migrating =====================================================
-- create_table(:toys)
   -> 0.0028s
==  CreateToys: migrated (0.0029s) ============================================

We can now start the server and check that everything went good.

1
2
3
4
$ rails s
=> Booting WEBrick
=> Rails 4.1.0.beta1 application starting in development on http://0.0.0.0:3000
...

listing children empty

It looks fine, except for one thing: there’s no data displayed! Let’s add some entries manually.

listing children

Good. Now let’s give some toys to our boys:

toy successfully created

Done. But wait a minute: this view looks a bit… crappy, doesn’t it? We don’t want to see a reference to a child… just his/her name. Even the prices don’t look right.

Let’s generate the scaffold again, with some corrections.

1
2
3
$ rails g scaffold toy description:string{50} price:decimal{4,2}
      invoke  active_record
Another migration is already named create_toys: /Users/simo/Projects/DemoApp/db/migrate/20140209145850_create_toys.rb. Use --force to remove the old migration file and replace it.

Fair enough. We must destroy the entire scaffold before recreating it.

1
2
3
4
5
6
7
8
9
10
11
$ rails destroy scaffold toy
      invoke  active_record
      remove    db/migrate/20140208224426_create_toys.rb
      remove    app/models/toy.rb
      remove    ...

$ rails generate scaffold toy description:string{50} price:decimal{4,2} child:references
      invoke  active_record
      create    db/migrate/20140209145850_create_toys.rb
      create    app/models/toy.rb
      create    ...

Ok. Let’s give a quick look at the generated migration.

1
2
3
4
5
6
7
8
9
10
11
class CreateToys > ActiveRecord::Migration
  def change
    create_table :toys do |t|
      t.string :description, limit: 50
      t.decimal :price, precision: 4, scale: 2
      t.references :child, index: true

      t.timestamps
    end
  end
end

It looks right. Let’s run it!

1
2
3
4
5
6
7
$ rake db:migrate
==  CreateToys: migrating =====================================================
-- create_table(:toys)
rake aborted!
An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: table "toys" already exists: CREATE TABLE "toys" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "description" varchar(50), "price" decimal(4,2), "child_id" integer, "created_at" datetime, "updated_at" datetime) /Users/simo/.rvm/gems/ruby-2.0.0-p353/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `initialize'

Whoops! The table already exists. We should remove it first. Edit the migration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class CreateToys > ActiveRecord::Migration
  def change
    # This will do the work
    drop_table :toys

    create_table :toys do |t|
      t.string :description, limit: 50
      t.decimal :price, precision: 4, scale: 2
      t.references :child, index: true

      t.timestamps
    end
  end
end

And migrate again:

1
2
3
4
5
6
7
$ rake db:migrate
==  CreateToys: migrating =====================================================
-- drop_table(:toys)
   -> 0.0107s
-- create_table(:toys)
   -> 0.0109s
==  CreateToys: migrated (0.0220s) ============================================

Ok, we are ready to start the server again and see what changed.

1
$ rails s

That’s it. This is basically the process. It’s way too labourious, I know, but the truth is that we just can’t efficiently automate a process like this, because: what if we generate more migrations during the journey? We would have to delete them and recreate again the whole schema by running rails generate scaffold, rake db:reset and rerun the generate again and again… well, that sucks. At this stage we’ve got the point: it’s better to do it manually! Rails gives us tons of helper methods to format prices and get things done, and that’s definitely the path to follow.

If you are still not convinced, you can check this question on StackOverflow. Basically, it’s almost the same question I had before writing this post. Both the question and the answer are quite old, and in the meantime the Rails Team didn’t develop anything that would help us regenerating our views. This probably means we are not supposed to do it, don’t you think? However, if your goal is to get focused on the backend without having to deal with the frontend, you can always use a gem like ActiveScaffold. But you have been warned!

I hope you’ve found this article useful; thoughts are welcome, as always. If you want you can leave a comment below.