You’ve probably already found some Ruby symbols, often used as hash keys.
Example :

{:foo => 'bar'}

:foo is a symbol. ‘bar’ is a string. But we could do :

{'foo' => 'bar'}

So why use symbols ? Let’s suppose the following case :

x = :sym
y = :sym

(x.__id__ == y.__id__ ) && ( :sym.__id__ == x.__id__)

This comparison will return true.
One same symbol will always be the same object in memory in your whole application. But that’s not a problem as symbols are not mutable.

And the same with strings :

x = "string"
y = "string"

(x.__id__ == y.__id__ ) || ( "string".__id__ == x.__id__)

Here, x, y and « string » are three different objects with different __id__. So 3 objects have been initialized in memory.

Now let’s take again our first hash with the comparison string/symbol.
With the symbols version :

{:foo => 'bar'}
{:foo => 'doe'}

We create 5 objects in memory : two hashes, a symbol and two strings.

With the strings version :

{'foo' => 'bar'}
{'foo' => 'doe'}

Here, we create 6 objects in memory : two hashes and 4 strings.

In an example case like this one it won’t change anything. But in a real application context, if you replace all your symboles by strings, you’ll need to increase the memory needed to run your application
So whenever it’s appropriate, stop using strings ans use symbols :)

When you get user information in console, you might, sometimes, need to get sensible information. Password for example.
Which can’t be displayed on the screen for security reasons.
The library Ruby Password allows you to do that quite easily.
However it implies you depend on this library. And that’s something I don’t wish. Particularly for something so simple.

The solution I’m suggesting here uses the linux features (not tested on windows. But who’s still using it today ? :mrgreen: ).

begin
    print "Username: "
    username = $stdin.gets.chomp

    print "Password: "
    # We hide the entered characters before to ask for the password
    system "stty -echo"
    password = $stdin.gets.chomp
    system "stty echo"
rescue NoMethodError, Interrupt
    # When the process is exited, we display the characters again
    # And we exit
    system "stty echo"
    exit
end

What are we doing ?
We start by asking the user’s nickname.

print "Username: "
username = $stdin.gets.chomp

This is not a sensible data and can be displayed. Nothing specific to do.

Then we ask for a password. Here we must hide it.

print "Password: "
system "stty -echo"
password = $stdin.gets.chomp
system "stty echo"

The « stty -echo » will hide every character that should be displayed on the console.
The « stty echo » displays them again.

Until there is works. Cool !
But somehowe we have a boring user, whom decides at the last moment to enter Ctrl-C to quit the program and finds himself in console with the -echo mode and doesn’t see what he enters in. We’ve just lost a friend.

Fortunately we have exceptions notifications and we already detect an Interrupt to exit the program cleanly.
Then we just have to display the characters again when there’s this interrupt :)

begin
    # ...
rescue NoMethodError, Interrupt
    system "stty echo"
    exit
end

Hop ! :)
And the project that uses this is glynn :)

I’m used to, when I want to update my local git repository with the distant one, to use git pull.
It works well. Until …

A few days ago, I wanted to release the version 1.0.0 of jesus. And to do so, I wanted to update the documentation.
The principle is simple. I use GitHub Pages. So I need a branch « gh-pages », which content is what’s online at GitHub for my documentation.
Whenever I commit on that branch, the online page is updated.

However my two branches master and gh-pages doesn’t have the same index. So they can’t be merged !
So I did

git pull origin gh-pages:gh-pages

Thinking « I get the content of my documentation branch ».
And I see a dozen of conflict errors ! WTF as we should say.

And I should have done

git fetch origin gh-pages:gh-pages

The difference between those two commands apparently similar is huge.
Git fetch only gets the datas. Git pull gets them and merges them with the current branch …
So when merging my two branches, as they don’t have the same base, it’s not cool.

Morality : you can git fetch when you want to update your local copy with the last distant commits. The branch on which you do the fetch will have the last commits.
But your working branch won’t be modified.
If you do a pull, not only the branch where you do the fetch will have the last distant commits. But your working branch will also be merged with those last commits.

After a second thought, fetch seems highly more recommandable that pull, which can break a repository pretty easily.

Some time ago, a PHP wanabee (berk), Romain was looking to make a web page screenshot only with command line.
Many solutions have been proposed. But my prefered one is Selenium. So I’ve decided to look closer into that.

First you need to have Selenium RC installed and launched.
It’s pretty simple. Download it, go to the selenium-server-1.0 and enter in command line

java -jar selenium-server.jar

Your Selenium server is started on the 4444 port, ready to be used !
You also need the selenium-client installed.

sudo gem install selenium-client

Your hard drive is now a bit less empty. We can start having fun with code ! :)
I want to do a screenshot of my portfolio.

We start with the magic and explain after.

require 'rubygems'
require 'selenium'

# We load Selenium
@selenium = Selenium::SeleniumDriver.new("localhost", 4444, "*firefox", "http://42.dmathieu.com/", 10000);
@selenium.start

# We go to the main page and take the screenshot
@selenium.open "/"
@selenium.capture_entire_page_screenshot(File.expand_path(File.dirname(__FILE__)) + 'screenshot.png', '');

# We unload Selenium
@selenium.stop

We load the required libraries. Not complicated. We only need Selenium.

require 'rubygems'
require 'selenium'

Then we load Selenium, indicating the URL we wish to visit and the browser with which we want to visit it.

@selenium = Selenium::SeleniumDriver.new("localhost", 4444, "*firefox", "http://42.dmathieu.com/", 10000);
@selenium.start

We load the page, take the screenshot and save the created image.

@selenium.open "/"
@selenium.capture_entire_page_screenshot(File.expand_path(File.dirname(__FILE__)) + 'screenshot.png', '');

And we don’t forget to free the memory.

@selenium.stop

And then the magic happens. Our beautiful screenshot (of the entire page, not only the screen) is then generated.

You’ll notice that javascript is executed (try to deactivate it on your browser, you won’t see my email on the page anymore).
And the render is what we have in the browser.

So who’s ready to start an open source project to generate websites thumbnails using Selenium ? :p

A few weeks ago, I started to look at god. It’s a great tool to manage a machine’s processes.
However I noticed one big problem: checking the status of god via SSH is everything but cool.

So I though why not start something, an interface between god and us, poor humans down there ?
And there was born (not in a manger and not from Mary) jesus.

It’s goal is pretty simple: provide you with a web interface to view the processes managed by god.
For example, here’s a screenshot of the version 0.0.1 (we’re currently in 0.0.2).

Jesus is a Sinatra app and must be started as the same user than god (mongrel and unicorn allows pretty easily to start processes as root).
It sill needs to be quite improved. But you can already use it and view all the managed processes.

Feel free to report any bug and to fork the project and contribute to it :)

When you’re looking to create charts in Ruby, you might spend quite some time searching a cool tool.
I’ve been, for example, falling on gruff this morning.

But the graphs created with that kind of tools are always dependant of some libraries, and many times, they don’t look very nice.
So I’ve been working on something new, using something not new :mrgreen:
You’ve probably already heard of Google Charts, which allows you to create some cute charts.

Now you can use it with Ruby and Rails with my new plugin, Ruby on GChart.
You provide your datas, the type of graph you want and it gives you the URL to see the graph :)
You can even save this graph to a file and use it locally.

Here’s an example of what you can do :

GoogleChart::Chart.new({
    :type => :line,
    :height => 200,
    :width => 500,
    :encoding => :simple,
    :datas => [70, 25, 50, 35, 150],
    :labels => ['First Label', 'Second Label']
}).to_url

It supports simple and text encoding (with the parameters :simple and :text). No extended encoding for now.

However it supports muliple graphs in multi levels array.
Example :

:datas => [[5, 10, 15], [10, 15, 5]]

You can put as mush graphs as you wish of course.

So what do you think of it ?

I’m a bit obsessed by my applications statistics.
So on many of them, I build tools allowing me to generate graphics with several evolution indicators of theirs datas over time.
On RefStats for example, this graphic shows the evolution of the number of positions; the number of users; of websites and the average execution time for the crawler.

Moreover, you probably already know the rails commande rake stats which gives some statistics datas on your application code.
Number of code lines, number of test lines, …
The class that builds it is located in the railties.
Unfortunately this class isn’t abstract at all. It shows directly the datas to the console. Not very cool to enter them to your database.

So I’ve taken this class to update it and allow you to get those datas in an abstract way and use them in an application :)
So let’s me introduct you to Rails Code Statistics (yeah my projects names are always very original)

The principle is pretty simple.
You instantiate the class :

stats = CodeSearch.new

Then you can the datas as an hash :

p stats.to_h

As a json element :

p stats.to_json

Only the total statistics

p stats.total

Only the detailed statistics

p stats.statistics

And then do whatever you want with them :)
For me for example, I have a rake task which is executed automatically once a day and puts the number of code and test lines to my database.
Then I only have to manipulate this database to build a graph.

Note : the version above will only work if you’ve made your tests with RSpec.
If you use Shoulda, I let you do it yourself :mrgreen:
And if you use Test::Unit, I invite you to try RSpec. You will not want to do anything else after :mrgreen:

The Django’s automatic administration generator is nice. With three lines, you have an interface to add, update and delete datas.
However with textareas, it might be useful to have a more advanced editor.

So we’re going to see here, how to implement TinyMCE to the textareas in a specific administration page.
But this technic can also work with FCKEditor or any other WYSIWYG editor. All you have to do is put the appropriate javascript.

Let’s our application’s admin.py

from django.contrib import admin
from project.application.models import Page
class PageAdmin(admin.ModelAdmin):
    list_display = ('name', 'url')
    fieldsets = [
        (None, {'fields': ['name', 'url']}),
        ('Content', {'fields': ['content']}),
    ]
admin.site.register(Page, PageAdmin)

We define an admin interface for our model Page with the fields name, url and content.
It’s the last field that will be a TinyMCE field.

Let’s start by adding external javascript files for this model.
After fieldsets[], add :

class Media:
    js = (
        '/js/tiny_mce/tiny_mce.js',
        '/js/admin_pages.js'
    )

We include those two supplementary documents in the admin page for the model Pages. And only this one.

Install tinymce in the folder /js/. And create the file /js/admin_pages.js in which you’ll put :

tinyMCE.init({
    mode : 'textareas',
    theme : "simple"
});

So you’ll transform any textarea in this page to a TinyMCE field (in our case, there’s only one).
Restart your application and look at your nice text editor :)

You can now add any javascript to any admin page this way.

If you’ve already been using Active Record. And as you’re reading this blog and this article, I suppose you have, even though you may not know you have, you know how it is powerful.
In case your memory fails you, active record is the list of methods used to access databases in Ruby on Rails.
It is compatible with MySQL, SQLite and PostgreSQL (and if you wish to add your own adaptor, you can quite easily).
But Rails is a framework for web applications. And God knows the web isn’t the only face of computer programming.
So we’ll see how easy it is to use Active Record without Rails (or without all rails as activerecord is a part of it).
First of all, you need to install the library. If you already Rails installed on your server, you’re ready to go. Otherwise, do the following :

gem install activerecord

It’ll get the latest stable version of the library and install it on your computer.

Now, let’s start having fun with some code lines :)

Create a new document named (for example) main.rb.

First, you need to call the rubygems and activerecord libraries.

require 'rubygems'
require 'active_record'

With those lines at the top of your document, you now have access to all the methods provided by Active Record.

So let’s use them.

ActiveRecord::Base.establish_connection(
    :adapter => 'mysql',
    :host => 'localhost',
    :user => 'root',
    :password => 'root',
    :database => 'test'
)

This will instantiate the library.
<em>However, it'll not connect you to the database. You're getting connected only when you do the first query</em>

We now need to create a model.
I invite you not to create it in the same document. So create a document named "user.rb" in the same directory as your main.rb.
Put in that new document :
[code lang="ruby"]class User > ActiveRecord::Base
end

And in your main.rb, call it.

require 'user'

You now have access, in your main.rb, to the object User, which is a child of ActiveRecord::Base and grants it all the usual methods available to Ruby on Rails models. However, you're not in a rails application.
So let's get all our users.

p User.find(:all)

Based on the fact that the table "users" exists in your database "test", this will print in your console the hash of all your users.

You can now do anything you want using ActiveRecord in your Ruby console or offline user interfaces applications.

But wait it's not over. Until now, we've defined all our configuration datas directly in the program. And that's very bad. So we need to add an external database.yml document.

adapter: mysql
host: localhost
username: root
password: root
database: refcrawler_dev

And to load that external document in ours to get it's values.

require 'yaml'
dbconfig = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)

This is the first article of a serie of comparisons between PHP and Ruby.

Count the number of words in a text is much more complex than what you should think first.
Because a space doesn’t  mean a new word everytime. There can be interrogation points with spaces before and after for example. And an interrogation point isn’t a word.

Here, we’ll take the following definition for « word » :
Two or more characters with at least one alphabetical character..

In other words : at leat two characters with at least one letter of the alphabet.

Let’s count our words in Ruby :

class String
    def nb_words
        self.split(/[a-z]+/).size
    end
end

To count the number of words, we only have to do :

puts "my string ! Great no ?".nb_words

Which will then give us 4 and not 6. « ! » and « ? » aren’t words.

Let’s now do the same thing in PHP.
Even though I don’t think it’s a good idea as there’s the function str_word_count.

function nb_words($string) {
    return count(preg_split('[a-z]+', $string));
}

To be used like the following :

echo nb_words('my string ! Great no ?');
 
Fork me on GitHub