You are currently browsing the category archive for the 'Ruby' category.

What is a scripting language?

From Wikipedia we read that:

Scripting languages (commonly called scripting programming languages or script languages) are computer programming languages that are typically interpreted and can be typed directly from a keyboard. Thus, scripts are often distinguished from programs, because programs are converted permanently into binary executable files (i.e., zeros and ones) before they are run. Scripts remain in their original form and are interpreted command-by-command each time they are run. Scripts were created to shorten the traditional edit-compile-link-run process.

Of course any self respecting computer scientist knows that definition is meaningless, because a language is a mathematical construct
and is not tied to its implementation. You can write a C interpreter, for example (and there are some). You can also write a compiler for any ‘interpreted language’ (of course the term ‘interpreted language is also meaningless). And there are theoretical constructs (Futamura projections) that given any interpreter are able to build a compiler from it (you could implement them even in practice, though it would be terribly inefficient).

However, any other definition would be misleading as well: if you define a scripting language as a language you can use to “script” (as in “bash script”), then you’ve got definition that’s even more stupid. bash is a scripting language, and so it is Python. However, if someone writes an application that is scripted in C, C becomes a ’scripting language’).

Both definitions have an additional problem: scripting languages are considered somewhat inferior to ‘non-scripting languages’. Some even use the term ‘true programming languages’ (and this ‘true programming languages’ are usually considered to be C and C++, for example).

Lisp, Haskell, OCaml, Prolog

In this dissertation on ’scripting languages’, Lisp is quite emblematic. Lisp can be compiled (there are some Lisp compilers around). But Lisp can also be interpreted. This is one of the most
widespread Lisp environments (and it is an interpreter). Moreover, in Emacs you can just run some Lisp snippets. And Emacs itself is scripted in Lisp (thus Lisp would be a scripting language according to the second definition). However, no one can assert that it is not a ‘true’ programming language. Emacs itself is a beautiful (and complex) piece of software, and a lot of ‘real’ (and extremely difficult) stuff in the AI field has been written in Lisp.

Haskell can be another example. Hugs is an interpreter, ghc is both an interpreter and a compiler. And Haskell is even statically typed (so you see, being dynamic is
not necessary ). The very same applies for OCaml or Prolog. And all this
languages have been used by the most theory-oriented computer scientist to
implement real programs.

I suppose nobody would say that Lisp or Haskell are ’scripting languages’ (even if according to the definitions they are — Haskell is used in many configuration tools by Linspire programmers).

Bash, Perl, Python, Ruby.

All this languages have been labeled as ’scripting languages’. And in fact according to definitions, they are. However, they are very different languages.

Bash is a very simple language designed to do simple things. Unix system administrators used it intensively (along with awk and sed and other utilities) to automate many repetitive tasks. Although this is surely ‘programming’, in some sense it’s different from programming an application from scratch. Some even consider it a ‘lower level’ kind of programming (and surely we must recognize that skills involved in writing a boot script are different from skills used to write a compiler)

Perl was born in this environment: its goal was textual manipulations and interactions between processes in a system. It is a nicer alternative to bash + awk in many situations. Later it has been added a fully fledged object model, but in the while it has been used to write very complex applications that go outside the ‘lower level programming domain’ that is usually associated with ’scripting’. Even though I don’t like Perl anymore, it is a general purpose language, with the same dignity of C or C++.

The ’scripting language’ monicker is not fitting anymore. And it is even less fitting for Python. Python has been an object oriented programming language from the beginning. Good software engineering practices have always been employed. However, many consider it just another scripting language. And of course Python makes a great scripting language.

The domains in which Python excels are the same in which Java is used, for example. However, Python can be used for scripting, too. That is to say… some (and I’d be tempted to say ‘most’ ) ’scripting languages’ can be used both as general purpose languages and automation/scripting.

The reason why they can be used for automation/scripting and that they are easier to use and we can write programs faster. The development cycle is faster, too. And to me, they all seem good properties.

I think that the very same features that make Python (or Ruby) great for scripting, make it even greater for general purpose programming. That is to say we should consider a ’scripting language’ not a poorer language, but a better one (yeah, of course this is exaggerated, since there are languages suited for scripting that are not suited for general purpose programming — AppleScript and bash, for example).

I usually call one single emacs server (I’ve got (server-start) at the very beginning of my .emacs), then connect to it with some emacsclient.

Unfortunately enough emacsclient just quits if there is no active emacs server.

I need a process that tries to run emacsclient: if there is no active server, it runs emacs.
Moreover, emacsclient has a -n switch that makes it return ASAP, so the terminal is available for more commands.
emacs has not such a switch, but that behaviour is the one I want.

So I decided to write a small ruby script that does just this:

  1. Tries to run emacsclient with the -n option.
  2. If it succeeds, we are done. Otherwise we run Emacs doing some
    standard posix process manipulation in order to return to the shell as soon as possible.

This is the script:

#!/usr/bin/env ruby

fork do
  exec('emacsclient', '-n', *$*)
end
Process.wait
if $?.exitstatus != 0
  fork do
    Process.setsid
    Signal.trap('HUP', 'SIG_IGN')
    exec('emacs', *$*) if fork.nil?
    exit!(0)
  end
  Process.wait
end

I recently bought the Ruby Cookbook. I bought the italian version (whose title is ‘Ruby Cookbook con elementi di Rails’ which roughly translates to ‘Ruby Cookbook with elements of Rails’). However, the book itself is not different.

Although I prefer to read technical books in English, I often buy books in Italian in order to show the publisher interest on that particular technology. In fact, in a country where most people avoid buying book in English because they feel they are ‘too’ difficult (like in Italy), good technologies do not spread if there are no good books in the local language.

The first impression with the book has been terribly negative. Actually if instead of buying the book online, I found it in a shop and leafed through it, I suppose I would have put it down.

Strings in Ruby are much like strings in other dynamic languages like Perl, Python
and PHP. They’re not too much different from strings in Java and C. Ruby strings are dynamic, mutable, and flexible.

In this paragraph you learn that “Ruby strings are dynamic, mutable, and flexible.” And that is true. However, you get another impression: the authors do not know what they are talking about.

They say that Ruby strings are ‘much like’ the strings in Perl. This is almost true (well, Perl unicode support is much better than Ruby, and Perl deals natively with unicode strings. However, saying that Ruby strings are like Python strings is plainly wrong: Python strings are immutable and are somewhat more akin to Ruby symbols (in fact if you call intern on a Python string you get something semantically very similar to a Ruby symbol). Moreover, Python deals with unicode natively.

Again, the comparison with Java strings is plainly wrong: in Java strings are immutable. The comparison with C is terrible: in C, strings are not even a primitive data type.

As I said before, at this point I was tempted to put the book on a shelf and never open it again. Luckily enough I went on and soon enough I found out I bought one of the best books on Ruby available.

The impression that the authors are not competent (or at least they speak of something they do not know) is plainly wrong. A few chapters later, there are some chapters that quite accurately confront Ruby pragmatic with Python one. They are poignant and precise: definitely the authors know both languages quite well. I suppose the ‘bad’ paragraph at the beginning was a tentative to be didactical.

The book in fact is quite didactical. You can read it with almost no previous knowledge of Ruby. The reader is guided through Ruby syntactical conventions (for example when dealing with strings, you learn that parentheses are optional, which is known to everybody who coded a bit in Ruby).

In the later chapters (most notably the ones on modules and objects), the reader learns the nature of Ruby power, and how to reason and develop in order to unleash that power. This book is a cookbook, but every single receipt does more than teaching a way to achieve its goal: it teaches something about the way Ruby programmers should think and code *in general*. In fact you can consider this cookbook a ‘beginner’ book that teaches by examples (and that is a very effective way in a language such as Ruby). Of course, there is also plenty of intermediate and advanced stuff, or subjects not covered elsewhere (for example the ones about image manipulation).

This is a precious book and the ideal companion for everyone who’s seriously motivated in learning Ruby. But it is also a book that a Ruby programmer may want to keep on her desk to find out how to do things without reinventing the wheel.

Introduction

Ruby is the new boy in town. Until a couple of years ago, nobody really
spoke about Ruby. It was really popular in Japan, but outside it was just
one of the many ’scripting’ languages that the open source world has
developed over the years.

The big names were using Python or Perl. Well, most of them were using PHP,
but in fact this does not matter: while Perl, Python and Ruby are excellent
languages (even if it is almost impossible someone really likes both Perl
and Python, nonetheless Perl has its merits), PHP plainly sucks.
And then of course
there was that Java everybody was talking about and C# (but the open source
guys usually said positive things about it only if in the same sentence
the word ‘mono’ occurred).

In the last few years Rails changed things. Now a lot of people are talking
about Ruby and dynamic languages. A lot of Java developers discovered the
power of dynamic languages and dynamic typing, after years spent saying
that the only saviour was static typing. In fact it seems to me that there
is kind of a revolution in the IT world.

Python and Ruby and Lisp and …

Rails is a pretty good framework. The documentation is acceptable even for
those who grew up with Sun’s bloated documentation (I still prefer to read
the code if the language itself is readable enough).

Ruby is a really nice language. In fact you can see it as a (Perl–)++.
It kept almost all nice features from Perl, and dropped some of the worse.
Of course a Perl Monger would disagree, but I’m a pythonist after all.

One of the most interesting things, in my opinion, is that Ruby and Python
are quite similar (even if they start from different points of view). I feel
quite comfortable with both languages, and even their pragmatic is not
really
different. Moreover differences tend to depend on different
syntax, rather than on different semantics.

For example in Ruby is quite frequent to ‘open’ classes and add methods.
This is something you can do in Python, even if there isn’t a special
syntax.

>> class A(object): pass
  >> a = A()
  >> a.foo()
  Traceback (most recent call last)
  ...
  <type 'exceptions.AttributeError'>: 'A' object has no attribute 'foo'
  >> def ext_foo(self): print 'foo'
  >> A.foo = ext_foo
  >> a.foo()
  foo

Of course this is far less elegant, and that’s way it’s something less
frequently done in Python.

Ruby has another ‘advantage’ over Python. It’s syntax is less rigid,
and in fact the most typical thing that is in Ruby pragmatic is to
write a DSL in the language itself and program in that DSL.

There are a lot of examples of this strategy in Rails itself. However, this
approach is not new at all. Lisp programmers have been using it since the
beginning, that is to say it’s almost forty years they code DLS in Lisp and
use them to write the application.

Duck typing vs. duck hyping.

Unfortunately I hear people saying quite often that ‘Ruby invented duck typing’. People that just
discovered Ruby, seem quite certain about it. Some of them even told me that
in Python you ‘were not really duck typing’ and that it was something
peculiar to Ruby. But let’s look at the definition (from Wikipedia):

Duck typing is a form of dynamic typing in which a variable’s value itself implicitly determines what the variable can do. This implies that an object is interchangeable with any other object that implements the same interface, regardless of whether the objects have a related inheritance hierarchy. Duck typing is a feature of programming languages such as Smalltalk, Python, Ruby, and ColdFusion.

Of course this is something that you can do in Python. And you can also do it in Objective C, by the way. And in Python it is something plainly obvious, too. Everybody does it, everybody likes it. But nobody thought about using a fancy name when describing the practice in books and blogs.

Amazingly, the term ‘duck typing’ (that some think it’s a Ruby peculiar feature) was probably used for the first time by Alex Martelli when speaking about Python typing system. It was Jul 26 2000, and the english language Ruby newsgroup had been active since the first days of may. There was a mailing list of course, but nonetheless Ruby was relatively unknown outside Japan.

In other words, don’t check whether it IS-a duck: check
whether it QUACKS-like-a duck, WALKS-like-a duck,
etc, etc, depending on exactly what subset of duck-like
behaviour you need to play your language-games with. If
the argument fails this specific-ducklyhood-subset-test, then
you can shrug, ask “why a duck?” (at least, you can if you’re
a Marx Brothers fan and have memorized “Cocoanuts”‘ script;
Monty Python one-true-wayists will have to find their own
simile here), and move on to the next set of tests (why-a-no-
chicken immediately comes to mind, but then one would have
to ask why it crosses the road, so I think we’d better snip it).

Alex’s original post

That is the reason why I say that Ruby supports ‘duck hyping’. Ruby is a very good language. I suppose that if I learnt Ruby before Python, I’d probably like Ruby more than Python (because the languages are quite equivalent, it’s my head that now works in a somewhat more pythonic way). However, there are a lot of people that are really *good* at selling Ruby. An excellent publisher based his early success on Ruby books, the creator of Rails has lots of marketing skills, and so on.

However, I was wondering: why Ruby and not Python? I don’t believe in fortune. To discover the answer (that in this particular case I guarantee it’ s not 42) we must analyze in which ways syntactical features of Ruby (since semantically they are quite interchangeable) influence the language pragmatic, and in which ways the pragmatic contributed to build Ruby success.

And when we are into pragmatic, we are not in the world of the compiler: we are in the world of the programmers. That is to say: we must understand why Ruby has appeal even where Python has not. We must understand in which way the language influenced the way of thinking of so many people, and why Python did not.

I’s a couple of day I’m hacking with xmodmap and keycodes to make my keyboard behave as I expect.
Recently it sprang to my mind that with SuSE 7.1 I used a utility called xkeycaps.

Unfortunately enough xkeycaps generates an .Xmodmap with keycodes expressed as hex numbers, while xev shows code as decimal numbers

This simple ruby oneliner converts an .Xmodmap file with hex codes to one with decimal codes

cat .Xmodmap.hex |
ruby -n -e "if $_ =~ /keycode\s*(0x[A-F0-9][A-F0-9])\s*=\s*(.+?)\n/; puts \”keycode #{$1.hex} = #{$2} \” else puts $_ end”>
.Xmodmap.dec

provided you called the hex .Xmodmap ‘.Xmodmap.hex’.

Today, while checking my gmail account I read an ad about Servoy being an alternative to Ruby and Rails

Actually, I wanted to check out what was that. I thought about some crappy PHP framework that pretended to do what Rails just cloning its structure, but without Ruby power

In the homepage the first thing you learn about Servoy is that Ruby syntax is complex and that Rails has limited capabilities. Further analisys makes me think it’s a Java based environment scripted in Javascript. Basically they are asserting that Javascript syntax is clearer than Ruby one (which is debatable) and that a RAD like thing built on Java is less limited than Rails. Note that Servoy is not Java: it is something built on Java (so I don’t expect it to be as powerful as Java, or it would be as complex as well).
I’m not against RAD or ‘easy’ environments. I just find ridiculous when they say that Rails is limited (that is false) and that a closed component system is more complete.

Moreover, I don’t know anyone using this Servoy. I haven’t read about it on tech magazines, my fellow developers haven’t heard about it either. My opinion is that it’s a small environment tool that uses Rails popularity (as a comparison) to convince people to pay them for something they could have done easier in Rails.

The same conclusions have been made by this blogger

Background

My development style is heavily test driven. One of the very first things I do write are fixtures, in order to write tests on them. For this reason the very first database I use in a Rails projects is the test database, rather than the development one.

When I have to populate the development db, I already have plenty of fixtures: if they aren’t enough to try the user interface (that is what is left to do), they weren’t enough to test the models and the controllers.

Of course this should be no problem, there is the rake task db:load:fixtures that plays well with this kind of issues. However, I tend to use db constraints rules such as

  ALTER TABLE bars ADD FOREIGN KEY(`foo_id`)  REFERENCES foos  (`id`) ON DELETE CASCADE;

if you use MySQL or

  ALTER TABLE bars ADD CONSTRAINT valid_foo FOREIGN KEY (foo_id) REFERENCES foos (id) MATCH FULL;

if you use Postgres.

Solution

Of course, in this case you can’t load fixtures in any order and you must supply correct fixtures loading order.

After some searching I found this solution.

However, it does not work. In fact it builds a Hash inserting fixture names in the specified order, than builds an array with other fixtures that had not been specified as needing some particular order.

Eventually, it sums the keys of the hash and the array, and loads fixtures in this order. I don’t understand how the poster got this code working, since Ruby Hashes are not ordered in any way and the documentation explicitly says that iterators and methods return values in arbitrary order and do not rely on insertion order.

This meant I had to change the code. Now it uses arrays everywhere (which seems the most reasonable thing to do, since this rake task it’s about order). I also added namespaces.

You still have to define something like

  ENV["FIXTURE_ORDER"] =
    %w( entities interaction_sources interaction_devices
        payments interactions accounts employments
        enrollments payables receivables tenures wards ).join(’ ‘)

My code is

  require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")

  ENV["FIXTURE_ORDER"] ||= “”

  def print_separator_line(n=80)
    puts “\n” + ‘=’*n
  end

  desc “Load fixtures into #{ENV['RAILS_ENV']} database”

  namespace :db do
    namespace :fixtures do
      task :load_ordered => :environment do
        require ‘active_record/fixtures’

        print_separator_line
        puts “Collecting specified ordered fixtures\n”

        ordered_fixtures = ENV["FIXTURE_ORDER"].split
        fixture_files = Dir.glob(File.join(RAILS_ROOT, ‘test’, ‘fixtures’, ‘*.{yml,csv}’))

        other_fixtures = fixture_files.collect { |file| File.basename(file, ‘.*’) }.reject {|fx| ordered_fixtures.include? fx }

        ActiveRecord::Base.establish_connection(ENV['RAILS_ENV'])

        all_fixtures = ordered_fixtures + other_fixtures
        print_separator_line
        puts “Fixtures will be loaded in following order\n”

        all_fixtures.each_with_index do |fx, i|
          puts “#{i+1}. #{fx}”
        end

        print_separator_line
        puts “Actually loading fixtures to #{ENV['RAILS_ENV']} db…”

        all_fixtures.each do |fixture|
          puts “Loading #{fixture}…”
          Fixtures.create_fixtures(’test/fixtures’,  fixture)
        end unless :environment == ‘production’
        # You really don’t want to load your *fixtures*
        # into your production database, do you?
      end
    end
  end
admin:
  id: 1
  login: admin
  salted_password: <%= LoginEngine::AuthenticatedUser.salted_password
		(LoginEngine::AuthenticatedUser.hashed("salt-#{Time.now}"), 			LoginEngine::AuthenticatedUser.hashed('atest')) %>
  salt: <%= LoginEngine::AuthenticatedUser.hashed("salt-#{Time.now}") %>
  email: admin@company.com
  verified: 1

This way you always generate fixtures that behave correctly according to your salt and such. Otherwise I had problems when doing “rake load_fixture” in the development db (the login failed).

Of course to render a rjs that has a name different from the controller method, we must use the :action specifier. For example we could have something like:

    respond_to do |wants|
      wants.html {render  :partial=>"post", :object=>@post, :layout=>'posts'}
      wants.js   {render  :action=>"remote_show"}
    end

Although this is pretty obvious if you reason about it, you may need some time to get it. And on the net there aren’t easily accessible examples about it (or at least I found none).

It’s just a dirty trick.

Inspired by a discussion on the Italian Ruby mailing list, I decided to write (probably another) pattern matching implementation for ruby. In the short term I want to be able to define something like:

func :qsort, [] { [] }
func :qsort do | list |
       qsort( list.select {|a| a <  list[0]} )  +
          list.select {|a| a == list[0]}    +
   qsort( list.select {|a| a >  list[0]} )
end

and if I find time it could become even some kind of “declarative like” unification algorithm… who knows. The point is I don’t even know if I have enough time for the “toy” pattern matching.

If you do something like:

page.replace_html 'non_existent', 'some text'

you get a Javascript error and sequent lines are not processed. The first idea to solve this problem would be

if page['not_valid']
page.replace_html ‘not_valid’, ’some text’
end

However, you don’t get what you meant. Not at all. This is translated to

$("not_valid")
Element.update("not_valid", "some text");

The best way I found do express that meaning is

page.select('not_valid').each do |unique|
page.replace_html unique, 'some text'
end

That works.

In tempi di Duck Typing ridiventa certamente di moda la distinzione fra classi e tipi che si trova per esempio nel capitolo introduttivo di Design Patterns di Gamma, Helm, Johnson e Vlissides.

La maggior parte delle persone sono oggi abituate a linguaggi come Java o C++ dove classi e tipi in buona sostanza coincidono (con la possibile eccezione della programmazione generica).

Un tipo è il nome usato per denotare una particolare interfaccia. Questo non ha direttamente a che vedere con le Interfaces del Java, per inciso. L’interfaccia è l’insieme di metodi (o di messaggi, per dirla con Ruby, Smalltalk o ObjectiveC) cui un oggetto risponde.

Tuttavia un oggetto può implementare diversi tipi, e tipi diversi possono essere condivisi da oggetti molto diversi fra loro. In questo i tipi si comportano come le interfacce Java. Qualunque programmatore Java sa che ci sono Interfacce (uso il maiuscolo per indicare che intendo la parola nel senso “Javesco”) supportate da diversi oggetti (leggi Cloneable, per esempio) e che un qualunque oggetto può implementare un numero grande a piacere di Interfacce.

La differenza è che le Interfacce di Java sono statiche e “legate” alle classi. Una data classe dice di implementare un certo numero di interfacce. Le istanze di quella classe avranno quindi per tipo le varie interfacce.
In Ruby tuttavia questo non accade. Un oggetto ha un dato tipo perché risponde a determinati messaggi, ma non specifichiamo da nessuna parte quale sia il tipo. Per il solo fatto di rispondere a certi messaggi un oggetto è di un dato tipo (a prescindere dalla sua classe). I tipi sono “informali” (usando la stessa differenza fra protocolli formali e informali di ObjectiveC — i protocolli formali si comportano sostanzialmente in modo simile alle Interfacce di Java, quelli informali sono appunti “non staticamente tipizzati”).

La classe è invece legata direttamente all’implementazione. Citando DP del GOF
“È importante capire la differenza fra la classe di un oggetto e il suo tipo. La classe definisce come è stato implementato. Definisce il suo stato interno e l’implementazione delle sue operazioni. D’altra parte il tipo di un oggetto si riferisce solo alla sua interfaccia, all’insieme di richieste a cui può rispondere. Un oggetto può avere molti tipi e oggetti di classi differenti possono avere lo stesso tipo

Naturalmente c’è una una stretta parentela fra classe e tipo. Poiché una classe definisce le operazioni che un oggetto è in grado di eseguire, definisce anche il suo tipo. Quando diciamo che un oggetto è un’istanza di una classe, diciamo implicitamente che l’oggetto supporta l’interfaccia definita dalla classe.

Linguaggi come C++ e Eifell (e Java ndt) usano le classi per specificare
sia il tipo di un oggetto che la sua implementazione”

D’altra parte linguaggi dinamici come Ruby o Python (o Smalltalk) non dichiarano i tipi delle variabili. Mandano messaggi (o chiamano metodi, per dirla con Python) agli oggetti denotati dalle variabili e se tali oggetti supportano il messaggio, tutto funzionerà.

La differenza fra ereditarietà di classe e ereditarietà di tipo è importante. L’ereditarietà di classe riguarda definire l’implementazione di un oggetto attraverso l’implementazione di un altro oggetto. È senza dubbio un concetto “DRY”. Se ho già definito delle cose (e gli oggetti sono sufficientemente vicini) posso mantenerle uguali. In Ruby a questo si associano i mixin che permettono di condividere codice *senza* andare in ereditarietà (ma questa è un’altra storia), in Python si può usare l’ereditarietà multipla per emulare i mixin.

L’ereditarietà di tipo è invece relativa all’utilizzare un oggetto al posto di un altro. In questo senso siamo più vicini al Principio di Sostituzione di Barbara Liskov. Un ottimo articolo relativo al LSP si trova qui . In buona sostanza possiamo enunciare il Principio di Sostituzione di Liskov come:

T1 è un sottotipo di T2 se per ogni oggetto O1 di tipo T1 esiste un oggetto O2 di tipo T2 tale che per ogni programma definito in termini di T1 il comportamento del programma è invariato sostituendo O2 al posto di O1.

Confondere ereditarietà di tipo e di classe è facile. Molti linguaggi non hanno alcuna distinzione fra le due. Anzi, vengono usate le classi per definire i tipi. Molti programmatori per esempio vedono il LSP solo in relazione alle sottoclassi (in effetti in C++ è importante fare in modo tale che gli oggetti si comportino “bene” in relazione al LSP, in quanto è sempre possibile fare puntare un puntatore o una reference di un supertipo ad un oggetto del suo sottotipo).

In realtà il principio di Liskov è una cosa *molto* severa. Due oggetti sono sostituibili secondo Liskov se davvero (limitatamente al tipo comune) si comportano allo stesso modo, e viene naturale pensarli come classe - sottoclasse (anche se effettivamente questo *non* è necessario).
Il DuckTyping è meno severo: non chiede che il programma abbia lo stesso comportamento. Due oggetti sono appunto sostituibili se rispondono alle stesse cose, anche se rispondono in modo diverso. Non ha *nulla* a che fare con il Design By Contract: è molto più vicino a quello che in C++ si fa con i templates (che alcuni in effetti vedono come il corrispettivo statico del Duck Typing).

Tornando a noi, se un oggetto si comporta secondo un certo tipo (ovvero risponde ai metodi propri di quel tipo), allora trattiamolo come tale. Da cui: se si comporta come una papera, trattiamolo come una papera (Duck Typing, appunto).

Un linguaggio come Ruby rende *molto* problematico considerare come stretta la relazione fra tipi e classi. In ogni punto del programma (anche se non è sempre buona pratica farlo) possiamo cambiare il tipo di tutti gli oggetti di una data classe (aggiungendo o togliendo metodi alla stessa), o singolarmente ad un singolo oggetto. Sintomatico è in questo senso avere deprecato il metodo Object#type in favore di Object#class.

After generating fixtures from my development database (you can read about it here) I decided to make them nice.

Up to now, for example, Permissions were labelled permission_001 and so on. And that is quite counter-intuitive. A good convention to label permissions would be controller_action. For example:

user_new:
action: new
id: 19
controller: user

The same applies to roles (you can label them with their name) and permissions_roles (you can build the name from their associated role and permission names). This is what my small script does. It is a rake task.

desc "Labels Roles, Permissions and PermissionsRoles after their value so that
the fixture becomes more readable. You can specify the DIR where fixtures we want
to modify are."

require 'yaml'

class Hash
def find_item(key, value, default=nil)
each do |k, v|
return k if (v[key] == value) || (v[key] == value.to_i)
end
default
end
end

task :beautify_fixtures => :environment do
dir = ENV['DIR'] || “#{RAILS_ROOT}/test/fixtures”
db   = ENV['DB']   || ‘development’

File.cp “#{dir}/roles.yml”,             “#{dir}/roles.bkp.yml”
File.cp “#{dir}/permissions.yml”,       “#{dir}/permissions.bkp.yml”
File.cp “#{dir}/permissions_roles.yml”, “#{dir}/permissions_roles.bkp.yml”

permissions = YAML.load_file(”#{dir}/permissions.bkp.yml”)
roles = YAML.load_file(”#{dir}/roles.bkp.yml”)
File.open(”#{dir}/permissions.yml”, ‘w’) do |file|
permissions.each do |k, v|
controller = v['controller']
action =v['action']
file.write “#{controller}_#{action}:n”
v.each {|key, value| file.write ”  #{key}: #{value}n”}
end
end

File.open(”#{dir}/roles.yml”, ‘w’) do |file|
roles.each do |k, record|
file.write “#{record['name'].downcase}:n”
record.each {|key, value| file.write ”  #{key}: #{value}n”}
end
end

permissions = YAML.load_file(”#{dir}/permissions.yml”)
roles = YAML.load_file(”#{dir}/roles.yml”)
prs = YAML.load_file(”#{dir}/permissions_roles.bkp.yml”)

File.open(”#{dir}/permissions_roles.yml”, ‘w’) do |file|
prs.each do |k, record|
permission = permissions.find_item(’id’, record['permission_id'])
role = roles.find_item(’id’, record['role_id'])
file.write “#{role}_#{permission}n”
record.each {|key, value| file.write ”  #{key}: #{value}n”}
end
end

end

You can find a downloadable version here

This is a quite interesting thread on rails ml with the solution to my problem.

I wanted to generate fixtures automatically from my db. This is a rake action that does the job well. Just put it into lib/tasks/ and call it dump_fixtures.rake

    desc 'Dump a database to yaml fixtures.  Set environment variables DB
    and DEST to specify the target database and destination path for the
    fixtures.  DB defaults to development and DEST defaults to RAILS_ROOT/
    test/fixtures.'
    task :dump_fixtures => :environment do
       path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures"
       db   = ENV['DB']   || 'development'
       sql  = 'SELECT * FROM %s'

       ActiveRecord::Base.establish_connection(db)
       ActiveRecord::Base.connection.select_values('show tables').each do |table_name|
         i = '000'
         File.open("#{path}/#{table_name}.yml", 'wb') do |file|
           file.write ActiveRecord::Base.connection.select_all(sql %
    table_name).inject({}) { |hash, record|
             hash["#{table_name}_#{i.succ!}"] = record
             hash
           }.to_yaml
         end
       end
    end

    # ActiveRecord::Base.connection.select_values('show tables')
    # is mysql specific
    # SQLite:  ActiveRecord::Base.connection.select_values('.table')
    # Postgres
    # table_names = ActiveRecord::Base.connection.select_values(<<-end_sql)
    #    SELECT c.relname
    #    FROM pg_class c
    #      LEFT JOIN pg_roles r     ON r.oid = c.relowner
    #      LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
    #    WHERE c.relkind IN ('r','')
    #      AND n.nspname IN ('myappschema', 'public')
    #      AND pg_table_is_visible(c.oid)
    # end_sql

Until a few days ago, I considered myself a “faithful” Pythonist. I liked ObjectiveC. I liked a bunch of other languages (notably Prolog or Haskell). I quite liked C++ too. But in fact my true love was Python.

I know it is strange to talk about “love”. That is of course unproper. Unfortunately I’ve no time to find a better word to express the thing. Let say that I liked to code in Python independently of what I was coding. Quite the same thing than I love using MacOS independently of the task, while I may be forced to use Windows because of the task, but would not use it if it was up to me (few… complicated period).

Today I read this (pointles) discussion about “self” in Python. There are people who

  • Does not like to self.foo
  • Does not like to
    def foo(self, else):
      # code
    

I perfectly understand this position. In fact I do not really like having to reference self explicitly everytime (even if I fully understand why python does this). Of course it makes sense.

I’m calling methods /accessing variables of an object. So I should use the conventional way object.method|variable. There should be only one way to do it. For example Java “optional”this sucks. At least in my opinion. It has no purpose in method/variable stuff. Some use it to make clear that they’re referencing instance variables, some use a m_var notation.
If you are a C++ programmer you could be using var_ or (if you haven’t read the standard quite recently) _var

Of course having a clear and readable way to distinguish instance variables methods is good. That is clear. It makes you easier to read.

self is boring. I often forgot it and got error messages (about the ninth consecutive programming hour this is not the worst thing I do, however). In this sense I also forget the ruby @. And it’s better a spectacular error than a hidden bug. So… go on

I quite don’t like having specify self among the formal parameters. You schiznick, don’t you know its a method? Actualy Python does not. If you take a normal function and bind it to an object, the first formal parameter is the object itself. So its better that function was meant from the beginning that way and had a starting self parameter.

Of course this is boring, but its necessary and has not real disadvantages (a part from some additional typing.. something that with a decent editor is not a concern Aquamacs/Emacs or TextMate strongly advised).

And so all the knots get back to the comb. Python has this boring self everywhere. And it is there and should be there. Ruby hasn’t.
The @ makes the code quite readable (expecially with a decent editor). Of course it prevents name clashes and such. Having not to pass self to functions also makes it easier to refactor from functions to methods (ok, we know, in ruby every function is a method, but that’s not the point). This in the case that the method uses no instance variables.

But…

But Ruby treats variables and methods differently. Instance variables need a “special” syntax. Methods don’t. It’s not clear if a method is a function or not (of course it does the Right Thing)

    irb(main):001:0] def foo; "foo"; end
    =] nil
    irb(main):002:0] class Bar; def foo; "dont foo" ; end
    irb(main):003:1] def bar; foo; end
    irb(main):004:1] end
    =] nil
    irb(main):005:0] b = Bar.new
    =] #
    irb(main):006:0] puts b.bar
    dont foo
    =] nil

As I said it does the Right Thing… I’m just talking about readability. Of course you can use self in ruby too… but well. This is something I would have preferred solved in another way, even if right at the moment I’m find quite acceptable to renounce to have “one way” for a bit more pragmatism.

First of all, I love %w{ }. It is wonderful. When prototyping it makes me save lot of digits. I know it’s a bit perlish (exspecially because you can also %w[ ] or %w/ /), but it is a great feature.

The %x{ } for commands (and ). Yeah, perlish. But I needed it in some system automation scripts in Python. I know I could use subprocess… but sometimes I need something more stupid. I wrote a class for this (and you can find it in my blog).

Regexps… I’m a python fan… but I have to admit perl’s syntax makes a lot of sense (and it is the one I have in sed or vim too, at least to some degree). Quite like that syntax in a cleaner environment.

Having the % operator on strings is good. It resembles me Python. I suppose it’s a bit less powerful (I think it works only with lists, but since you can use #{} in ruby strings, the need for dictionaries is small). Moreover some of the most un-pythonic code I wrote is due to “creating” dictionaries. If you don’t take care, you may find yourself with troubles. Of course even the #{} can be abused and so be source of problems.

<< on strings and arrays. I quite liked streams in C++. Yeah, not the same thing, but…

I’ll write more later… (there are also things I don’t like, but I should study more to fully understand them).

One of the first things you learn when reading a book on Ruby is that “variables” hold references to objects. Consider


a = Foo.new
b = a

Both a and b contain the same instance of the object. Fine. Simple. Java does the same and so does Python. You just know what that means and you know that if you want a copy instead (that is to say b and a should change indipendently) you must dup or clone them.


a = Foo.new
b = a.dup

Now it comes to arrays. Ruby arrays are much like Python list. They are powerful objects. And have something Python lists do not have, some more constructor. From the ruby doc:

Array::new
Array.new(size=0, obj=nil)
Array.new(array)
Array.new(size) {|index| block }

Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element’s index to the given block and storing the return value.

We analyze the very first constructor. It makes perfectly sense: consider this:

  l = Array.new(5, "") # ["", "", "", "", ""]
  l[1] =”foo”
  l # ["", "foo", "", "", ""]

Now consider this:

    l = Array.new(5, []) # [[], [], [], [], []]
    els = %w{ el1 el2 el3 el4 el5 }
    l.each_index { | index | l[index].push els[index] }
    #  [
    #    ["el1", "el2", "el3", "el4", "el5"],
    #    ["el1", "el2", "el3", "el4", "el5"],
    #    ["el1", "el2", "el3", "el4", "el5"],
    #    ["el1", "el2", "el3", "el4", "el5"],
    #    ["el1", "el2", "el3", "el4", "el5"]
    #  ]

This is the correct result. But this probably is not what we wanted to obtain. The “correct way to initialize l” would have been

    l = Array.new(5) { | dummy | Array.new } # [[], [], [], [], []]
    els = %w{ el1 el2 el3 el4 el5 }
    l.each_index {| index | l[index].push els[index] }
    # [["el1"], ["el2"], ["el3"], ["el4"], ["el5"]]

This time for each line we are creating a “new” empty list, not the very same one.

In this case you probably should have been using the Matrix class, anyway.

In fact this is not a Ruby vs. Python list. I know not enought Ruby and I love Python to much :). It’s more a picture of the first impressions I had on Ruby after I seriously began studying it.

This is a quick list of thoughts. I’m probably adding more stuff later. In fact I’m reaaly amazed. Ruby is really hackish, but it’s also neat and clean. It may sound strange… but I’m afraid I’m gonna love ruby more than Python: it addresses many of the things I come to dislike in Python.

Some stuff I like

  • Adding dynamically stuff to classes. The syntax is clean and obvious

    class MyClass
      def aMethod
        puts "Called aMethod"
      end
    end
    
    m = MyClass.new
    
    begin
      m.aMethod2
    rescue NoMethodError => ex
      puts "Failed to call #{ex}"
    end
    
    class MyClass
      def aMethod2
          puts "Called aMethod2"
      end
    end
    
    m.aMethod2

    In Python for example it is not that clean. The ruby code looks more like ObjectiveC categories (even if in fact you don’t specify a category, of course, since ruby does not need categories).

  • private, protected, public modifiers. Being dynamic they do not limit me in any way (if I need I can dynamically change this)
    class MyClass
      protected
      def aMethod
        puts "Called aMethod"
      end
    end
    
    m = MyClass.new
    
    begin
      m.aMethod
    rescue NoMethodError => ex
      puts "Failed to call #{ex}"
    end
    
    class MyClass
      public :aMethod
    end
    
    m.aMethod

    Moreover I can’t think to a cleaner syntax to do this. Of course one can argue that they aren’t really necessary. Of course, but if you want they do give you a little bit of control, but they don’t limit you in any way.

  • Object#freeze: if you suspect that some unknown portion of code is setting a variable to a bogus value, try freezing the variable. The culprit will then be caught during the attempt to modify the variable.
  • I love postfixed control clauses. In fact if used with moderation they can augment code readbility (and of course if abused they make it less readable). However, it is pretty logigal to say do_something if something_else. In fact since ruby has blocks it is ok also to write
    begin
        # some stuff
    end if condition
    

    maybe not everyone agrees

  • Accessors are great. Using attr and similar constructs is great. I also find quite more readable to “assign” with foo= than using more Javesque setFoo(val). In fact properties in Python work in a similar fashion, even if maybe a bit more verbose (however, I think they make it clearer how to document code, but this is a ruby aspect I’ve not yet exploited)
  • Gems: I think python needs something like that. Pimp is not that good, in my opinion, of course.

Stuff I don’t know if I like or not

  • Not having to write parentheses with no-argument methods. I’ve not yet discovered if I like it or not.
  • All the $_… They are used a lot in Perl. I like it, but I’m afraid it can mess things up.

Stuff I dislike

  • I don’t like passing strings to require. In fact it can have advantages, but I prefer the pythonic import foo to require “foo”.
  • The try catch semantic of try/catch, makes me think to some kind of disguised goto. I’m sure I’m wrong… but
  • I’d like to have something like Perl use strict;. It’s something I miss in Python (even if with pychecker you can just live without it). Now I’ve got to find some kind of “use strict” or “rubycheck”.
  • Assignment is an expression. This directly leads to code like
    a = true
    b = false
    print b if b=a
    

    and we imagine the programmer wanted to write

    a = true
    b = false
    print b if b==a
    

    However in Ruby almost everything is an expression, and it has quite a lot of advantages. So we have to tolerate the “=” for “==” problem.

Today I decided to take some time and have a look at Ruby. I found online a version of Programming Ruby and started reading it. In fact I knew I was going to like Ruby. In fact the first time I took contact with it I quite liked it, even if I didn’t fully exploit its capabilities.

Well… let’s see how it goes. Right at the moment the first thing I wrote is

class Employee
  attr_reader :wage, :name
  attr_writer :wage

  def initialize(name, surname, wage)
    @name = name
    @surname = surname
    @wage = wage
  end

  def surname
    @surname
  end

  def to_s
    "#{name} #{surname} (#{wage})"
  end
  protected :wage=

end

class Manager > Employee
  def initialize(name, surname, wage, employees=[])
    super(name, surname, wage)
    @employees = employees
  end

  def setWage(emp, wage)
    emp.wage = wage
    emp
  end

  def to_s
    super + @employees.collect{|e| “\n  #{e}”}.join(”")
  end
end

mr = Employee.new(”Jack”, “Bravo”, “1000€”)
mc = Employee.new(”Michael”, “Charlie”, “300€”)
mngr = Manager.new(”Angus”, “Smith”, “10000€”, [mr, mc])
mngr.setWage(mc, “700€”)
puts mngr