Subscribe to XML Feed
21 Jan 2010

Simple Mustache JSON Serialization

If you’ve taken a look at Mustache, the “stupid in a good way” templating engine, you might know that there are also Javascript Mustache renderers such as Mustache.js. Today I’ve released a small library called mustache_json that allows you to compile your Mustache view objects into JSON, allowing them to be interpreted by Javascript Mustache rendering engines.

What this means for your project is that you will finally have a identical client-side and server-side rendering interface, opening wide the opportunities for pushing more of the rendering work onto the client-side, a boon for many real-time and heavy-interaction applications.

To install mustache_json, just get the gem from Gemcutter:

gem install mustache_json

To use it, simply require 'mustache_json' and all of your Mustache objects will automatically be given a #to_json method. For instance:

require 'mustache_json'

class Person < Mustache
  def initialize(first_name, last_name)
    context[:first_name], context[:last_name] = first_name, last_name
  end
  
  def initials
    "#{context[:first_name][0..0]}.#{context[:last_name][0..0]}."
  end
  
  def listing
    "#{context[:last_name]}, #{context[:first_name]}"
  end
end

bob = Person.new('Bob', 'Bobson')
bob.to_json

This will render into a JSON object that looks like this:

{"last_name":"Bobson","initials":"B.B.","listing":"Bobson, Bob","first_name":"Bob"}

Mustache JSON gives you access to all of the public instance methods you declare in your Mustache as well as any context you have set. It is essentially a fully compiled version of the Mustache view, providing everything another renderer needs to create the actual markup. The JSON back-end for this library is swappable, meaning you can use the JSON gem, JSON pure, ActiveSupport, or Yajl by default (and any other class with an encode method if you’ve got a different library).

Documentation is available on RDoc.info and the source is available on GitHub. Stay tuned for posts in the future about utilizing this library to actually perform identical rendering in Ruby and Javascript.

View Comments
12 Nov 2009

Hashie: The Hash Toolkit

One of my earliest gems was Mash, a useful tool for creating mocking objects as a Hash. One of the most common problems people had with Mash was a simple one: it conflicted with another class of the same name in extlib! To address this problem as well as give the project some room to grow, Mash is now part of a new toolkit called Hashie. Hashie is available now via Gemcutter and the source, as always, is available on GitHub. To install:

gem install hashie

Hello, Hashie

Hashie is, right now, simply the former Mash code along with a new extended Hash called a Dash. A Dash is a “discrete hash” that has pre-defined properties. It can be used as a dead-simple data object when even something like DataMapper is too heavy, but a Struct is too light (Dash gives you the ability to set per-property defaults as well as initialize from an attributes Hash). For example:

class Person < Hashie::Dash
  property :name
  property :email
  property :occupation, :default => 'Rubyist'
end

p = Person.new
p.name # => nil
p.occupation # => 'Rubyist'
p.email = 'abc@def.com'
p.email # => 'abc@def.com'
p['awesome'] # => NoMethodError

p = Person.new(:name => "Awesome Guy")
p.name # => "Awesome Guy"
p.occupation # => "Rubyist"

The other advantage Hashie has over Mash is that it’s built from the ground up to avoid conflicts. Instead of adding stringify_keys methods to the Hash class, it’s instead added to a Hashie::Hash subclass. You can, however, get Hashie’s few Hash extensions in the Hash class by including the HashExtensions:

Hash.send :include, Hashie::HashExtensions

Hopefully the move will make it easier for everyone to use it in their projects without fear of running into conflicts, and hopefully you’ll also find the Dash useful. Over time the functionality of Hashie may grow to encompass additional simple and useful extensions of Hash. So install Hashie, your friendly neighborhood Hash toolkit, today!

View Comments
03 Nov 2009

Rails Quick Tip: Readable Conditional Validation

This is something that many may already use as a best practice, but if not it’s something simple and convenient to add to your repertoire. Sometimes you may have a model that requires additional information if a certain condition is met. For example, I may require a user to add more information about themselves if they wish to be listed publicly, whereas I would not if they do not wish to be listed. By combining ActiveSupport’s Object#with_options and ActiveRecord’s conditional validations, we can implement this behavior in a straightforward and readable manner (assuming here that there is a boolean field called “listed” in the database that is exposed as a checkbox or similar to the user):

class User < ActiveRecord::Base
  # Our standard validations
  validates_presence_of :login
  validates_uniqueness_of :login

  # Validations for listed users
  with_options :if => :listed? do |l|
    l.validates_presence_of :email
    l.validates_length_of :description, :minimum => 100
  end
end

It’s a simple technique that piggybacks off of Rails’s automatic construction of existence query methods (in this case, listed?) for fields in the database combined with the mapping power of with_options and standard conditional validations.

View Comments
22 Sep 2009

TweetStream: Ruby Access to the Twitter Streaming API

Twitter’s Streaming API is one of the most exciting developments in the Twitter API in some time. It gives you the ability to create a long-standing connection to Twitter that receives “push” updates when new tweets matching certain criteria arrive, obviating the need to constantly poll for updates. TweetStream is a Ruby library to access the new API.

Installation

Installation of TweetStream is simple, it’s available as a gem on GitHub and Gemcutter.org. To install it from GitHub:

gem sources -a http://gems.github.com
gem install intridea-tweetstream

To install it from Gemcutter:

gem sources -a http://gemcutter.org
gem install tweetstream

Usage

TweetStream creates a long-standing HTTP connection to Twitter, so unlike other Twitter libraries you don’t simply run it once and deal with the results. Instead, you provide a block that will be yielded to with each new status that arrives. The most basic example is:

require 'rubygems'
require 'tweetstream'

TweetStream::Client.new('user','pass').sample do |status|
  puts "[#{status.user.screen_name}] #{status.text}"
end

This will provide you with a small sample snapshot of all of the updates being posted to Twitter at this moment and print them to the screen. There are also methods available to track single-word keywords as well as the updates of a specified list of user ids (integers, not screen names). You can do that like so:

# Track the terms 'keyword1' and 'keyword2'
TweetStream::Client.new('user','pass').track('keyword1', 'keyword2') do |status|
  puts "[#{status.user.screen_name}] #{status.text}"
end

# Track users with IDs 123 and 456
TweetStream::Client.new('user','pass').follow(123, 456) do |status|
  puts "[#{status.user.screen_name}] #{status.text}"
end

Daemonization

One of the most useful features of TweetStream is its built-in daemonization functionality. This allows you to create scripts that run in the background of your machine rather than taking up an active process. To create a daemon script, you simply use TweetStream::Daemon instead of TweetStream::Client. Here’s an example:

require 'rubygems'
require 'tweetstream'

# The third argument is an optional process name.
TweetStream::Daemon.new('user','pass','tracker').track('keyword1','keyword2') do |status|
  # Do something like dump the status to ActiveRecord
  # or anything else you want.
end

If you were to place the above code in a file called tracker.rb you could then run ruby tracker.rb to see a list of daemonization commands such as start, stop, or run.

TweetStream is a simple wrapper on the Streaming API, but with built-in daemonization provides powerfully flexible means of accessing the Twitter Streaming API using familiar Ruby tools. More complete code documentation is available at rdoc.info.

View Comments

Older Posts

CouchDB-Lucene, CouchDBX, and CouchRest 21 Sep 2009 Comments
A Fresh Coat of Paint 20 Sep 2009 Comments
Good Idea, Bad Idea: Rails Rumble Post-Mortem 24 Aug 2009 Comments
Quick Tip: Railsy Array Checks in jQuery 19 Jun 2009 Comments
Make it so with RSpec Macros 15 May 2009 Comments
TwitterAuth Supports 'Sign in with Twitter' 17 Apr 2009 Comments
Present.ly Nominated for the WebWare 100 31 Mar 2009 Comments
Using Git Submodules for Shared Application Components 25 Mar 2009 Comments
TwitterAuth: For Near-Instant Twitter Apps 23 Mar 2009 Comments
Yet Another Twitter Monetization Strategy: 'Claimed' Hashtags 18 Mar 2009 Comments
The Case For GitHub Canonization 03 Mar 2009 Comments
Quick Tip: Rails URL Validation 18 Feb 2009 Comments
Utilize Canonical URLs in Your Rails Apps 13 Feb 2009 Comments
Outsource Your Blog 11 Feb 2009 Comments
Open Source Is Amazing 11 Feb 2009 Comments
Moving to Jekyll 10 Feb 2009 Comments
It's No Joke - Real-Time Search is a Big Deal 09 Feb 2009 Comments
SASS: The Better, More Powerful CSS 04 Feb 2009 Comments
Use MacFUSE to Make a Boxee Torrent Dropbox 02 Feb 2009 Comments
The Case For Web Applications 02 Feb 2009 Comments
HasAvatar: Defining an Application Vocabulary 28 Jan 2009 Comments
Twitter Search Plus: Find Replies Inline With Twitter Search 22 Jan 2009 Comments
Sort Your Files By Date 04 Dec 2008 Comments
The Importance of External Downtime Resources 28 Nov 2008 Comments
Hacking the Mid-End (Great Lakes Ruby Bash Edition) 11 Oct 2008 Comments
Colorist: Color Manipulation for Web Heads 18 Aug 2008 Comments
Fetches: Bringing Your ActionController Its Slippers 28 Jul 2008 Comments
Using HTTP Status Codes for Rails AJAX Error Handling 23 Jul 2008 Comments
UberKit Update: UberForms to Ease Form Building 14 Jul 2008 Comments
UberKit: Building a Rails UI Swiss-Army Knife 07 Jul 2008 Comments
What the World Needs Now is CSS3 02 Jul 2008 Comments
Using RSpec and Autotest While Writing Rails Plugins 25 Jun 2008 Comments
SubdomainFu: A New Way To Tame The Subdomain 23 Jun 2008 Comments
GemPlugins: A Brief Introduction to the Future of Rails Plugins 11 Jun 2008 Comments
ActsAsTaggableOn Grows Up 09 Jun 2008 Comments