This post originated from an RSS feed registered with Ruby Buzz
by Gabriel Horner.
Original Post: Hirb - And Tables for All
Feed Title: Tagaholic
Feed URL: http://feeds2.feedburner.com/tagaholic
Feed Description: My ruby/rails/knowledge management thoughts
Almost a year ago, hirb started as an itch to get mysql-like tables for Rails’ ActiveRecord models. Now, hirb 0.3.0 provides table views for ten additional database gems. Whether you use hirb with couch, mongo, riak or any of the databases supported by sequel or datamapper, hirb essentially turns irb into a database-agnostic database shell.
Database Gems
Here are the list of additional database gems and their modules/classes that now have table views:
Here’s all you need in your ~/.irbrc for hirb to work with the above gems and the following examples:
require'rubygems'require'hirb'Hirb.enable
Keep in mind that while that the following examples are simple, your models/tables can be as complex as you’d like and hirb will still render your tables cleanly.
For this example you need to have CouchDB installed.
$ sudo gem install couchrest
$ irb -rubygems -rcouchrest
# Setup db and a model
>> class Url < CouchRest::ExtendedDocument
>> property :name
>> view_by :name
>> end
=> false
>> Url.database = CouchRest.database("http://127.0.0.1:5984/urls")
=> #< CouchRest::Database:0x170541c ... >
# Nicely formatted tables!
>> Url.create :name=>'example.com'
+----------------------------------+-------------+
| _id | name |
+----------------------------------+-------------+
| af990a562a9a96703dd6ef0442a73db8 | example.com |
+----------------------------------+-------------+
1 row in set
# Same as above
>> Url.all
Dynamic Views
Creating Them
All default views for the new database gems are due to hirb’s dynamic views. So what if you’re using a database gem that isn’t supported? Let’s answer this using friendly as an example (even though hirb already supports it):
Identify the module or class that the database gem uses to define models. For friendly, this module is Friendly::Document.
Determine what table options to pass to tables and how to generate them from the database gem’s model/table object. Although you can define as many options as you want, you must define the :fields option. To generate fields for a given friendly model object: model.attributes.keys
Using the last two steps, define a dynamic view using Hirb.add_dynamic_view that returns a hash of table options:
If you’ve created a dynamic view for a somewhat popular database gem, feel free to fork and add it to hirb’s default dynamic views. Since hirb’s default dynamic views are in module form, read the docs to understand how to write them. Although I do appreciate any forking, I’m looking mainly to add default views for commonly used database gems.