Skip to content

Rails flag_shih_tzu Plugin with named_scope

When it comes to store a load of boolean data into your model you easily end up with lots of columns which blow up your table unnecessarily. The developers at Xing solved this problem with a nifty Rails Plugin called flag_shih_tzu. The trick is to store all boolean values combined as a bit vector, which allows you to put up to 32 values (4Byte) within a single Integer column. Automatic generated access methods allows you to deal with you model as your are used to. Wanna see an example? (Taken from plugin docs)

[ruby]
class Spaceship < ActiveRecord::Base
include FlagShihTzu

has_flags 1 => :warpdrive,
2 => :shields

end

enterprise = Spaceship.new
enterprise.warpdrive = true
enterprise.shields = false
enterprise.save

enterprise.warpdrive? #=> true
enterprise.shields? # => false
[/ruby]

Nice, isn’t it?

Unfortunately named scopes where missing for selecting models easily. So another github fork, another fix, and here were are. Now this works as well:

[ruby]
Spaceship.flagged(:warpdrive).not_flagged(:shields).all
[/ruby]

Check it out here: http://github.com/rngtng/flag_shih_tzu/tree/master

Update: replaced ‘routes’ with ‘scopes’ - I’m getting confused with that all the time, how come!? ;-)