Increasingly Functional.
by Joshua Miller | on Twitter | on the web | on github

Loose Change Gets CoffeeScript Views

January 1st 2011

Tagged: couchdb

If you are using Loose Change in a Rails 3 app, version 0.4.2 brings you a Rake task, loose_change:views:push, that scans a directory structure for map and reduce views in JavaScript or CoffeeScript, compiling the latter, and pushing them to the correct design document. To use, make sure your Gemfile includes gem 'loose_change', '~> 0.4.2' and (if you want to use CoffeeScript), gem 'coffee-script. The default directory for view files is db/couch/views/ModelName/view_name/, but you can specify a custom value via rake loose_change:views:push["/path/to/custom/"].

As an example, say you had an Item model with name and description properties, and you wanted a view that would let you find documents by any keyword in those two properties, so that Item.by_keyword("shirt") would yield an Item with the name "Polo Shirt" and another with the description "A wonderful shirt for gifts."

First, we can write the map function, in CoffeeScript:

   (doc) ->
     if doc.model_name == 'Item'
       keywords = "#{doc.name} #{doc.description}".split(/\s+/)
       for word in keywords
         word = word.replace(/[^a-zA-Z0-9]/, '').toLowerCase()
         emit(word, doc) if word.length > 2

Here we just check that we're dealing with an Item model, then turn the name and description into an array of keywords, remove any special characters, downcase the keywords, and then emit the keyword as the key if its length is greater than 2 (tossing out 'it,' 'an,' etc.).

Put that code in db/couch/views/Item/by_keyword as map.coffee, run rake loose_change:views:push, and Loose Change will compile your CoffeeScript view to JavaScript, push it onto the design document for Item, and you'll have a method Item#by_keyword you can use to query your Items collection.