Friday, July 18, 2008

Rails + Gettext Crash Course, Part 1

This article is a short guide to how use gettext with ruby-on-rails. If you do not know gettext is the standard internationalisation (i18n) library of the GNU project http://en.wikipedia.org/wiki/Gettext. And this is the first part of the two articles. The second one might be found here.

Since there are some of i18n plugins for rails why should you chose gettext?

For some reasons.

First as I said it is the standard for GNU. Standard means wide support several tools to work with it, optimisation, documentation, etc. Most of Linux programmes use gettext.

Second, one of the key features of gettext is ability to use real, correct strings. You don't write strange keys in your code, you just put usual English phrases instead, like that

<p><%= _('Some text here') %></p>
<p><%= _('Length: <i>(%{min} min)</i>') % { :min => @min_chars } %></p>

As you see this allows you easily use any placeholders or html formatting tags in here if you need so. Another point for gettext is that you don't have to keep in mind the translation issues during the development time. You just put your text as nothing happened and always have a default translation with normal usual looking strings.

After you have done with the development you can parse out all the strings which need to be translated with special util. You will have standard formed .po file which you can then translate with some special programs, where you can use spellchecking versioning and all the civilize life advantages.

Third, this stuff can do lots of things, localize numbers, dates, currencies, work with pluralization on native languages and so one. Take a look at the official site for getting more information http://www.gnu.org/software/gettext/gettext.html

So how do we use the stuff with rails?

Quite simple.

First of all you need to install gettext by itself and rubysupport aka gem. Installation of gettext depends on your platform. With linux it's pretty simple. Say something like

# emerge gettext
or
# apt-get install gettext

Once you have installed gettext support, you need to install the gettext gem.

# gem install gettext

After it is done, you need to include it into config/environment.rb file of your rails project.

require 'gettext/rails'

After this you can start develop your project and use the _('text') constructions where you need to put some text.

If you are using Rails 2.1, there's a bug which have not fixed yet. But you can easily fix it by saving the following code into a file config/initializers/gettext.rb

# the gettext missed method fix
module ActionView
class Base
delegate :file_exists?, :to => :finder unless respond_to?(:file_exists?)
end
end

Once you have done with the development and want to create some translation you need to do some preparations.

First you need to add two simple tasks to your Rakefile.

require 'gettext/utils'
desc "Update pot/po files to match new version."
task :updatepo do
GetText.update_pofiles(
"my_site",
Dir.glob("{app,lib}/**/*.{rb,rhtml,erb,rjs}"),
"my_site version"
)
end

desc "Create mo-files for L10n"
task :makemo do
GetText.create_mofiles(true, "po", "locale")
end

The first one will scan though your source code and parse out all the strings which need to be translated and put them all into a .po file. The second one will compile all your translations into a standard .mo files which gettext can use.

So, you say 'rake updatepo' in your console and this will create for you the file named 'po/my_site.pot', this is template of your internationalisation. You copy the file in translation directories like that.

po/
de_DE/my_site.po
fr_FR/my_site.po
ru_RU/my_site.po
my_site.pot

Then you translate the .po files with one of the translation programmes, say this one http://www.poedit.net. Under Linux and KDE you can use standard KBabel programme, or under Gnome you can use the gtrasnlator project. Certainly you can edit those files just as plain text if you like so. Many texteditors support them.

Once you have done with the translation, run the 'rake makemo' task in your console and it will create the 'locale' directory in your rails project folder with a standard structure like that

locale/
de_DE/LC_MESSAGES/my_site.mo
fr_FR/LC_MESSAGES/my_site.mo
ru_RU/LC_MESSAGES/my_site.mo

This is almost it. You only need to initiate it in your application controller now.

class ApplicationController < ActionController::Base
GetText.locale = 'en_EN' # <- default locale
init_gettext 'my_site'

before_filter :define_language

def define_language
# here you can switch the locale on fly
# say like that

case params[:lang]
when 'de': set_locale 'de_DE'
when 'fr': set_locale 'fr_FR'
when 'ru': set_locale 'ru_RU'
else set_locale 'en_EN'
end
end
end

As you see we have used non existing locale 'en_EN', if there is no some locale your default strings from the source code will be used. So you always have a fallback language.

This is pretty much it for the start.

But remember with gettext you not only put some translated text-labels in your application, you easily can create translations of whole template files, you can translate models, values, format numbers, dates and do lot of another useful things.

Thursday, July 3, 2008

TestCase 2.0 is out

After several month of development, finally I have released the tool version 2.0

There is the release notes and short changelog

Download page

And now you can watch the project's demo

Saturday, June 28, 2008

Making Quicktime work in Ubuntu

There is a common issue with quicktime videostreams under linux. So this is a simple trick how you can make it working under the Ubuntu linux.

1) Uninstall all the video plugins you have got with your firefox installation (for example the vlc plugin)

2) Install the mplayer package and the quicktime extentions for it.

3) Install the mozilla-mplayer plugin

4) Reinstall firefox.

That's it. Go to apple.com/trailers, it should get working now

Monday, June 16, 2008

JavaScript Diff Function Implementation

Since I have not ever done it before, I have found it was not obvious to me how to create a lists diff function in JavaScript, so I feel like should public the solution.

function diff(first, second) {
var diff = [], start_k = 0;

// calculating the diff
for (var i=0; i < first.length; i++) {
var same_found = false;
var pluses = [];
for (var k=start_k; k < second.length; k++) {
if (first[i] == second[k]) {
same_found = second[k];
start_k = k+1;
break;
} else {
pluses.push(second[k]);
}
}
if (same_found) {
for (var j=0; j < pluses.length; j++) {
diff.push({plus: pluses[j]});
}
diff.push({same: same_found});
} else {
diff.push({minus: first[i]});
}
}

// pushing down the trailing elements
for (var k=start_k; k < second.length; k++) {
diff.push({plus: second[k]});
}

return diff;
};

this function will return a sequention of hashes with keys 'minus', 'plus', 'same' which represents the differences and similarities between the two incomming arrays

Wednesday, May 14, 2008

Tried KDE4 on Kubuntu

I've been testing Kubuntu with KDE4 today and have learnt two lessons.

1) There's nothing to be eager about KDE4. I mean, seriously, the guys do a good job, but this is still the same good old kde3. Those plasma and dolphin stuffs, doesn't change much, that's like a good version of the superkaramba project, it looks nice but practically doesn't change the workflow at all. And as 99% of applications still from KDE3, if don't mention internal changes, in really you've got a new nice theme for kde.

I'm little bit disappointed, the fourth version was anounced for good couple of years ago and then been delayed several times and as the result we've got something pretty raw and almost nothing new.

Yup, that's it, there's nothing in really why you should migrate to kde4 so far.

2) The quality of kubuntu is lower then the quality of ubuntu. Sorry gus, but that's true. There are several things which works out of box in ubuntu, but doesn't work in kubuntu. Several things are left behind in order to keep the kde-purity, that left a bad feeling.

Monday, May 5, 2008

Order By Aggregations With ActiveRecord

The issue is following, say you have got a classical structure in two models

class Order < ActiveRecord::Base
has_many order_items

def total_due
order_items.to_a.sum(&:total_price)
end
end

class OrderItem < ActiveRecord::Base
belongs_to :order

# and it has two principal fields
# decimal :price
# integer :quantity

def total_price
price * quantity
end
end

As you see the orders don't have own total_due fields, instead of this each order can calculate the value depend on the aggregated items. So, that's cool, we follow all the good design habits and keep the things clean.

But when you retrieve/display the orders list there might be a situation when a customer would like to order the list by the total_due value. Quite a natural desire, but there's the problem, we don't have the total_due field in really. It's virtual and depend on the aggregated objects.

Yes, you may reorder the items after retrieving, manually, but if you have quite a lot of orders and use a pagination you'll get back to the problem anyway.

The example is pretty simple, but you see, there might be lots of similar situations when you have some calculations on an aggregated data and would like to order your lists depends on the virtual fields.

So, how do we handle that?

We use the :select option for the ActiveRecord find method. Usually with the option you specify a number of fields you would like to extract, to not suck up heavy ones when you don't want them. But with the same option you may specify additional fields to extract and use all the power of SQL expressions. Those new fields will be added to the instanced object temporary, you can read them but you can't save them.

In our case this might be something like that

:select => "SUM(order_items.price * order_items.quantity) as total_due"

In the case we are using the SQL function SUM, calculate the total-due for each order, and then each selected order will obtain the total_due attribute after extraction and you may use it for your sorting options.

Then, as you see we mentioned the 'order_items' column in the select option, to make it working we should add a tables join and the items grouping options. The overall instruction might look like that.

Order.find(:all,
:select => "SUM(order_items.price * order_items.quantity) as total_due, orders.*",
:joins => "INNER JOIN order_items ON order.id = order_items.order_id",
:group => "order.id",
:order => "total_due"
)

After this you will need to fix your Order model a little, to make it use the temporary field when it appears

class Order < ActiveRecord::Base
def total_due
self[:total_due] || order_items.to_a.sub(&:total_price)
end
end

Yes, that looks a little bit sqlish dirty for a rails application, but then it works and does what you need.

And there's another issue with the solution. You actually cannot use the :include option with the :select option at the same time. That's usually not a big issue, just note, if you specify the :include option, your :select option won't work.

Friday, April 18, 2008

I think stories need chapters

This rspec's stories stuff is quite nice, I like it. But when I'm trying to write more or less complex story it turns out to a nightmare. It's quite hard to stay on the DRY way with the stories, you always need to repeat the stuffs again and again. Even if you organize your code in good and handy steps, you'll have to repeat them in the scenarios anyway.

So, I think it would be cool to have in the stories another level aka Chapter. Think even nested chapters. I could look like that.

Story "an item live-story" do
Chapter "items index" do
Given "two items"

Scenario "anonymous gets the index" do
Given "an anonymous user"
When "he GET /items"
Then "he should be redirected to the login_path"
end

Scenario "registered user gets the index" do
Given "a logged in user"
When "he GET /items"
Then "he should see the 'items/index' page"
And "both items should be on the page"
end

Then "something in common happens"
end
end

The idea is that the chapters were working like scopes for the inside subchapters and scenarios. You may specify there common givens and thens which will be applied to the internal parts. May be it could be useful to be able to attach additional steps for particular chapters.