labelize

This very very simple gem is handy for several things:

* Simplify creating select tags
* Easily outputs a model as a string
* Ads to_sentence functionality to a model
* Allows searching items by the defined label without changing controllers

First, define the label of your model (it must be a String column):

class Country
  label :name
end

Now you are free of “collects” or “collection_select”. Look:

- form_for(@state) do |f|
  = f.select :country_id

You can do that:

irb> country = Country.create :name => 'Brazil'
irb> puts country
Brazil
=> nil

And that:

irb> Country.to_sentence
=> "Brazil, Uruguay and Argentina"

At last, but not the least, you can find items by name automatically:

irb> Country.find('Brazil')
=> #<Country id: 72, name: "Brazil", ...>

If you have a specific label for searching (like a permalink column), you can set it as a second parameter:

class Country
  label :name, :permalink
end

irb> Country.find('south-corea')
=> #<Country id: 31, name: "South Corea", :permalink => 'south-corea' ...>

It works out-of-the-box with inherited_resources and i think it can be used with has_permalink also.

Install

Just add this to your Gemfile (assuming your source is RubyForge)

gem 'labelize', '0.1.3'

And then run

bundle install

Ideas

This gem is still beta, so please, if you have any thought on were the “labels” idea can also be usefull please feel free to share. My twitter is @joaomilho.

Rails version

Labelize is only tested with Rails 3.0.0.beta4. Upgrade baby!

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.

Copyright © 2010 Juan Maiz. See LICENSE for details.