Rails flag_shih_tzu Plugin with named_scope

2009 August 20

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)

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

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:

Spaceship.flagged(:warpdrive).not_flagged(:shields).all

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!? ;-)

One Response leave one →
  1. 2009 August 21

    Hi Tobi,

    very good idea!

    Please make sure to talk about “named scopes” instead of “named routes” here ;)

    As said already via private msg, I would prefer dedicated named scopes like
    Spaceship.warpdrive.all und Spaceship.not_warpdrive.all
    instead of the general ones using a symbol parameter.

    We should then extend the tests to really use ActiveRecord and check the generated named scopes.

    What do you think?

    Thanks,
    Sebastian

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS