Archive | Ruby on Rails RSS for this section

sphinx and WARNING: DOCID_MAX document_id, skipping

This error seems to wake-up with large ids >100.000.000 (like Ruby On Rails fixtures sys does).
Ok, like Piotr Jasiulewicz says this error appears because the sphinx was built without the –enable-id64 option.

Let’s go to solve this problem in Debian (note: I assume you use mysql, if not you have to change some dependencies packages).

Update 2012-05-31: this post refers to Debian Lenny i386. I don’t know if the binary package of Debian Squeeze (other distros, versions, architectures) is compiled with the same compile options at the moment. Anyway this post is intended to solve the specific warning (or to suggest a solution just in case you use another distro/architecture) .

Move to your preferred source folder (for example ~/src) or create it. Move to root user with su.
Download debian’s sphinxsearch sources:

#apt-get source sphinxsearch

Give permissions to your user on sphinxsearch files.

#chown -R youruser:youruser sphinxsearch*

Install mysql dev packages:

#apt-get install libmysqlclient-dev libmysqld-dev

Exit from root and return to your user. Enter in source folder of sphinxsearch (may vary with versions), configure with proper flags and make.

#exit
$cd sphinxsearch-0.9.9
$./configure –enable-id64
$make

Please note that pgsql is disabled by default and you should take a look at configure options (./configure –help) to see if you need others options, I don’t (except for libstemmer but I ignore this here).

Ok. If all was ok at make/compile time you can move on installation.

Move to root user with su (uninstall debian sphinx package if needed) and install.

#apt-get remove sphinxsearch
#make install

That’s all. Happy Sphinx On Ruby On Rails with fixtures 🙂

ruby on rails on nokia N900

Yes, we can! ruby on rails works well on nokia n900.
Install ruby from maemo repository (dev).
Download and install rubygems (use –no-rdoc and –no-ri).

Rubygems creates only /usr/bin/gem1.8 so you should create a soft link like this: ln -s /usr/bin/gem1.8 /usr/bin/gem

Type gem install rails -V and wait.

Now you are ready to start your rails app on nokia n900!
Just run ruby script/server in your project folder. To create a project folder use rails my_app as usual.

Your server may not start if you miss libopenssl-ruby. In this case you get an error about net/https: apt-get install libopenssl-ruby.

rails date validation, rails validate date for date_select

Ok, you are in right place if you need to validate a date from date_select helper.
Expecially if your problem is an invalid date like ’31/02/2009′  that becomes ’02/03/2009′ on rails!
If you don’t want to waste your time read here and don’t go immediatly to rails date validation plugin .

validates_timeliness plugin introduces a lot of great features to validate a date but its documentation is not so cool (this is my absolutely wrong opinion). You have to read it completly or take a look here about 3 important points:

  • I18n
    if you don’t use :en locale you have to implement validates_timeliness default translation in your translations file (for ex. config/locales/it.yml) or you will waste your time to debug stupid exceptions. Default plugin translation file can be found in vendor/plugin/validates_timeliness/lib/validates_timeliness/locale after installation;
  • Validate invalid date (like 31/02/2009 becomes 02/03/09) from select helpers
    You need to know that validates_timeliness doesn’t fix this problem automatically as you expect!
    You have to manually enable validates_timeliness workaround if you need to validate invalid date on rails.
    Put ” ValidatesTimeliness.enable_datetime_select_extension! ” your environment.rb (EOF) to enable validate_timeliness workaround and catch bad dates.
    Note: Patch to ticket #10556 introduced this problem: rails accepts invalid dates from input (instantiate Time object and convert it back to a date).  This problem generates a lot of confusion, checks on controllers, horrible workarounds and so on… A valid reason seems to exist! But WTF!!! People in panic and code with consistency problems…

Any other information (and download) can be find on validates_timeliness at github.

Have a nice day!

 

validates_timeliness

lighttpd, fcgi, rails and child exited with status 9, 1, 2, 3 or X

Ok, these errors are not good. They didn’t tell much about what happended.
But you can’t do as I did. Don’t wander on the dark side of the system…
Just try to execute your FCGI as your lighttpd did.
Find your lighttpd user in lighttpd configuration file (debian: /etc/lighttpd/lighttpd.conf).
On my configuration I see:
server.username  = “www-data”

so…

$ su
# cd /my_rails_root/public
# sudo -u www-data ./dispatch.fcgi

Read what’s happen and solve.
That’s all!

Validazione Codice fiscale Partita IVA con Ruby / Ruby On Rails

Cercando di validare codice fiscale e partita iva con Ruby, sono capitato nel sito di Umberto Salsi, dove si parla della validazione di Partita Iva e Codice Fiscale.

Visto che l’implementazione in Ruby non era disponibile ne ho realizzata una che ho già inoltrato all’autore della pagina perchè possa aggiungerla all’elenco.

Nel frattempo comunque, le due classi che ho preparato sono disponibili per il download.

Il codice Ruby che ho realizzato per eseguire i check di validità su codice fiscale e partita iva non è corredato da alcuna garanzia, potrebbe causare la morte di migliaia di persone, l’incendio del vostro PC, il mutamento del vostro orientamento sessuale, ma in nessun caso potrete ritenermi responsabile. Usatelo a vostro rischio e pericolo! 🙂

Scarica la validazione Ruby di codice fiscale e partita iva

updated (16/11/2009) – nuova versione con licenza GPL inclusa, descrizione, eccezioni e qualche miglioria

L’utilizzo è molto banale e potete riutilizzare, modificare e redistribuire il codice a vostro piacimento per qualsiasi utilizzo.

Un banale esempio di utilizzo per il codice fiscale:

require 'codice_fiscale'
if CodiceFiscale.valid?('ILTU0C0D1C3FISCAL3')
puts 'il codice fiscale è valido!'
else
puts 'il codice fiscale non è valido!'
end

Un banale esempio di utilizzo per la partita iva:

require 'partita_iva'
if PartitaIva.valid?('02030405060')
puts 'la partita iva è valida!'
else
puts '
la partita iva non è valida!'
end

Sull’opportunità o meno di utilizzare la validazione, vi consiglio di leggere il capitolo “Miti, superstizioni e falsità” sul sito di Umberto Salsi a proposito della validazione del codice fiscale. A tal proposito riporto riassumendo il concetto: usate la validazione ma non sempre è attendibile, potrebbe dare dei falsi negativi, bloccando per esempio la registrazione di utenti legittimi. Viceversa gli utenti malintenzionati potrebbero fabbricarsi in pochi secondi un codice fiscale falso (ma corretto) attraverso uno dei tanti servizi online. La validazione del codice fiscale risulta quindi utile solamente se si vuole eseguire un controllo formale per evitare errori di battitura, ma è solamente controproducente se si cerca con questo mezzo di tener lontano qualcosa e/o qualcuno.

Per quanto riguarda la partita iva vale quanto detto a proposito del codice fiscale.
Tuttavia ho individuato un bel webservice per la validazione delle partita iva messo a disposizione dell’Unione Europea e denominato VIES VAT number validation. Il wsdl e maggiori informazioni sul servizio potete trovarle nelle Faq. Il servizio peraltro funziona, l’ho provato oggi, ed è pure gratuito e discretamente veloce. Interroga i database dei paesi dell’Unione quindi è in grado di fornire validazione anche per le altre partite iva europee. Va sottolineato che non si limita a fare la validazione formale, ma da quanto si apprende attraverso le Faq è anche in grado di verificare se la partita iva esiste realmente ed è attiva. Per alcuni paesi inoltre, fornendo la partita iva, oltre a verificare se esiste ed è disponibile, vengono forniti anche alcuni dati utili sull’azienda tra cui nome ed indirizzo (l’italia è ovviamente esclusa da questa chicca).

Se qualcuno è interessato può scaricare la ruby class for VIES VAT number validation che ho realizzato per un applicativo su base Rails. Per altri usi dovete chiaramente adattarla, ma fa il suo dovere. Ricordate di copiare i wsdl in locale, è una scelta preferibile.

Buona giornata!

sanitize inline css with rails

Hi! You can simply use the sanitize(…) helper in your views to whitelist allowed tags and attributes… but what to do if you need to sanitize the content of a style attribute?  I found a solution to sanitize inline css with rails. This may not be the best solution available, but I didn’t find another solution (like an argument for sanitize helper).

Put this code in your config/enviroment.rb

# ALLOWED CSS PROPERTIES 
HTML::WhiteListSanitizer.allowed_css_properties = Set.new(%w(text-align font-weight text-decoration font-style))
# ALLOWED CSS PROPERTIES - acts like property_name-*, for example `text` allows text-align, text-deco...
HTML::WhiteListSanitizer.shorthand_css_properties = Set.new(%w())

Remember to restart your application, enviroment.rb must be reloaded also in development mode.

Have a nice day!

undefined method `length’ for Enumerable Enumerator on text_helper.rb:50:in `truncate’

With rails 2.0.2 and ruby 1.8.7 you can find this error using rails truncate helper

To solve this problem, paste this code in your enviroment.rb (eof).

module ActionView
  module Helpers
    module TextHelper
      def truncate(text, length = 30, truncate_string = "...")
        if text.nil? then return end
        l = length - truncate_string.chars.to_a.size
        (text.chars.to_a.size > length ? text.chars.to_a[0...l].join + truncate_string : text).to_s
      end
    end
  end
end

Have a nice day!

How to downgrade rails version on debian

If you want to downgrade rails (aka install an old version of rails) on debian first of all install rails gems. Execute next command as root:

apt-get install rubygems

Remove rails package of debian if it’s actually installed

apt-get remove rails

Now install rails by gems utility and force the right version. Example:

gem install -v=2.0.2 rails --include-dependencies

Now put gems bin folder on bash PATH. Edit /etc/bash.bashrc

export PATH=$PATH:/var/lib/gems/1.8/bin

Note: version of rubygems may be different, check your right PATH to gems bin folder

If all goes right now you can use your preferred rails version. Note, rails command from gems is little different between the script that debian package installs. Just check params: call rails command without params.

$ rails
Usage: /var/lib/gems/1.8/bin/rails /path/to/your/app [options]
Options:
-r, --ruby=path Path to the Ruby binary of your choice (otherwise scripts use env, dispatchers current path).
Default: /usr/bin/ruby1.8
-d, --database=name Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite2/sqlite3).
Default: mysql
-f, --freeze Freeze Rails in vendor/rails from the gems generating the skeleton
Default: false
Rails Info:
-v, --version Show the Rails version number and quit.
-h, --help Show this help message and quit.
General Options:
-p, --pretend Run but do not make any changes.
--force Overwrite files that already exist.
-s, --skip Skip files that already exist.
-q, --quiet Suppress normal output.
-t, --backtrace Debugging: show backtrace on errors.
-c, --svn Modify files with subversion. (Note: svn must be in path)

That’s all folks! 🙂

Estendere Ruby con C

Capita a volte di aver bisogno di estendere Ruby con codice C.
I motivi principali riguardano le performance dell’applicativo e la comodità garantita da un linguaggio di basso livello come C.
Altre motivazioni possono riguardare la necessità di utilizzare con Ruby una libreria C non disponibile in Ruby.

Nel mio caso ho trovato estremamente utile, se non del tutto necessario, utilizzare C per eseguire operazioni di compressione/decompressione con l’algoritmo di Huffman, in special modo sentivo particolarmente la mancanza dei comodi puntatori C.

Dopo una breve ricerca ho trovato un buon tutorial in lingua inglese su rubyinside.com.
Seguendo il tutorial potrete compilare la vostra libreria in C e creare un modulo da utilizzare per estendere una classe Ruby.

Per completezza, ho trovato anche altri metodi per ottenere risultati similari, tra i quali Ruby Inline, Swig e DL. A mio parere però, nessuno di questi metodi ha la linearità e la semplicità del metodo offerto da `How to create a Ruby extension in C in under 5 minutes` di Peter Cooper.

A breve creerò un tutorial per questa utile funzionalità.

Ruby on Rails & Compressed Prototype

Hello! Today I’m wandering about a compressed version of prototype to use in my brand new ruby on rails application.
Initialy I didn’t understand why rails doesn’t provide a compressed version of prototype but after some googling I’ve found some usefull answers.

Concept is simply clear.

Why use a compressed/packed version of prototype if we can provide it to clients throught gzip compression with best results? There isn’t a valid reason.
So we need to provide a gzip compressed version of prototype.

Read More…