Ein Rails-Plugin strippt AR-Attribute 0

Posted by fwoeck
on Thursday, April 09

Das Plugin strip-attributes entfernt Whitespaces vor und nach ActiveRecord-Einträgen. Perse leere Attribute werden ge-nil-t. Dadurch entfällt die lästige Prüfung und das manuelle Strippen. Achtung: das Plugin funktioniert über einen before_validation-Hook, d.h. es werden Attribute behandelt, bevor sie gespeichert werden – nicht nachdem sie gelesen wurden!

Die Aktivierung ist schnell getan:

script/plugin install git://github.com/rmm5t/strip_attributes.git

und für jedes Modell, das man behandeln möchte braucht es etwas wie:

1
2
3
4
5
6
7
8
9
10
11
class DrunkPokerPlayer < ActiveRecord::Base
  strip_attributes!
end

class SoberPokerPlayer < ActiveRecord::Base
  strip_attributes! :except => :boxers
end

class ConservativePokerPlayer < ActiveRecord::Base
  strip_attributes! :only => [:shoe, :sock, :glove]
end

Wie gesagt, der Strip geschieht vor der Validierung. Wenn man gelesene Attribute behandeln möchte, kann man sich damit behelfen, .valid? an dem Datensatz auszuführen:

>> u = User.find_by_firstname('Barbara ')
=> #<User oid: "1239070455218_JUser", isemployee: nil, login: ...

>> u.firstname
"Barbara " 

>> u.valid?
=> true

>> u.firstname
=> "Barbara"

Weblinks

github.com/rmm5t/strip_attributes