When it comes to backups, this gem has it all #

Backup, a tool written by Michael van Rooijen , has provided me so much value over the years that it’d be a shame not to give it some Changelog love.

Backup is a system utility for Linux and OS X which allows you to easily model your backup system using a nice Ruby DSL. The greatest thing about Backup, aside from the fact that it Just Works, is that it has built-in support for just about anything you would want to do.

It handles compression, encryption, cloud storage, splitting, syncing, notifications, logging, and on, and on.

With all that functionality, you might expect Backup to be overwhelming to get started with. Not so. It also has nifty generators which spit out documented model code so you can learn and tweak as you need. If that’s not enough, there is a Getting Started page and a very useful wiki which explains, in detail, all of the subsystems.

Backup is MIT licensed and hosted on GitHub.

Xray-rails reveals which files are being rendered in your view #

When I pair with Railsbridge attendees or new developers, I often wish I had a visual way to let them see the connection between the files in the codebase and what’s rendered in the browser. Today Ruby 5 featured Xray and a number of friends contacted me about checking it out. In no time I knew I’d found the solution.

I gave it a test drive on one of the student apps and it took 5 minutes, at most, to get up and running.

Just drop this in your Gemfile:

group :development do
  gem 'xray-rails'
end

Bundle and delete the cached assets:

$ bundle && rm -rf tmp/cache/assets

Restart your app, visit it in your browser, and press cmd+shift+x

xray-rails

By far the best feature in Xray is the fact that it allows you to actually click on the overlay and go straight to the file or partial being rendered. It defaults to Sublime, which is easy for new users, but is simple enough to customize to another tool for seasoned pros.

Xray is great for:

  • Helping new Rails developers while pairing to get clearer understanding of views
  • Gaining quick insight into complex views
  • Debugging templates, partials, and backbone views

See Xray in action

Right now Xray is a tool for the Rails framework but there are plans to expand and make it available for any framework. You can check it out on Github.

Write Ruby API’s with Stripe’s Poncho (a DSL for REST interfaces) #

As we said in a previous post: WE LOVE STRIPE!

The team at Stripe has open sourced a RubyGem that makes REST API’s easy to create, Poncho. It’s compatible with any rack-based framework — like Rails or Sinatra. Best of all, it has a slew of (simple to use) features:

Installation is simple, just install the poncho gem (or add gem poncho to your Gemfile). After installation, you can setup your API:

class ChargeResource < Poncho::Resource
  param :amount, :type => :integer
end

class ChargeCreateMethod < Poncho::JSONMethod
  param :amount, :type => :integer, :required => true

  def invoke
    charge = Charge.new
    charge.amount = param(:amount)
    charge.save

    ChargeResource.new(charge)
  end
end

post '/charges', &ChargeCreateMethod

The above code, which was pulled from the documentation is using Sinatra, but you could easily swap Rails out:

match '/charges' => ChargeCreateMethod, :via => :post

The documentation is thorough, and does a great job at explaining how to use Poncho. You can also view the source or discuss this on HackerNews.

Cache ActiveRecord models in Memcached with IdentityCache by Shopify #

As the quote says, Shopify took a step to open source their solution for caching ActiveRecord model objects in Memcached. An elegant solution backed by a powerful data store, IdentityCache has already been used in production. It’s fairly simple to install, straight from the README:

Add this to your Gemfile:

gem 'identity_cache', :git => 'git://github.com/Shopify/identity_cache.git'

Then bundle, and tell IdentityCache where Memcached is at:

config.identity_cache_store = :mem_cache_store, Memcached::Rails.new(:servers => ["mem1.server.com"])

Usage is even easier, again from the README!

class Product < ActiveRecord::Base
  include IdentityCache
  has_many :images
  cache_has_many :images, :embed => true
end

# Fetch the product by it's id, the primary index.
@product = Product.fetch(id)

# Fetch the images for the Product. 
# Images are embedded so the product fetch would have 
# already loaded them.
@images = @product.fetch_images

IdentityCache also has support for: Secondary Indexes, Caching Associations and more. Head on over to GitHub to View the README or the Source Code.

Ghost means never having to touch ssh/config again (either) #

As a throwback to our original coverage of Ghost back in 2010, I wanted to share a hidden feature I just discovered in Ghost.

Two years ago Felipe Coury submitted a pull request to add ghost-ssh to manipulate ~/.ssh/config files. If it weren’t for Google pointing me to this pull request, I would have never known ghost-ssh existed. The readme says nothing about it!

This is what Felipe had to say when he submitted his patch:

I had a need to manipulate ~/.ssh/config file the same way I can manipulate my hosts entries, so I made this change.

Not sure if it will be useful for the upstream project, but be welcome to merge if you like.

An intro to ghost-ssh

Just like with ghost on the command line, ghost-ssh has basic list, add, and delete options, as well as an import operation to import files.

To save you some time, here’s the contents of ghost-ssh --help:

$ ghost-ssh --help
USAGE: ghost-ssh add <host> <hostname> [--user=<user>] [--port=<port>]
       ghost-ssh modify <host> <hostname> [--user=<user>] [--port=<port>]
       ghost-ssh delete <host>
       ghost-ssh list
       ghost-ssh empty
       ghost-ssh export
       ghost-ssh import <file>

An example of adding a new entry to your ssh/config might look something like this:

$ ghost-ssh add tclprod xxxxxx.gridserver.com --user=tcladmin
  [Adding] tclprod -> xxxxxx.gridserver.com

You can confirm the entry was added to ssh/config by running the ghost-ssh list command:

$ghost-ssh list                                             
Listing 1 configs(s):
  tclprod -> tcladmin@xxxxxx.gridserver.com:22

Now that I have this new entry in place, I can easily ssh into the server by running ssh tclprod and boom goes the dynamite!

Checkout the source for Ghost on GitHub for install and usage details.

Discuss on Hacker News if you’d like.

Better Rails development with better_errors! #

If you are anything like me (a Rails developer that enjoys good design), you will be glad to know that there is a project out there to make the default error pages for Rails development much cleaner! The standard features are simple, and pretty much just a polished version of what Rails offers out of the box:

  • Full stack trace.
  • Source code inspection, with highlighting.

As a bonus, if you install the extra dependency, you get access to the following features:

  • REPL
  • Local/instance variable inspection.

Installing it couldn’t be easier. While the project is usable outside of Rails, let’s assume you are using Rails/Bundler:

group :development do
  gem "better_errors"
  gem "binding_of_caller" # Optional, only for the advanced features
end

That’s it! Checkout the project on GitHub or view the README.

Virtus – give your Ruby objects DataMapper-like attributes #

I’ve written a few wrappers for various JSON APIs, and each time I’ve had to make a decision about how to represent API data in Ruby. Ruby hashes and arrays work well but bracket['notation'], can be hard on the eyes and fingers. My go-to library for these types of objects is often Hashie, the hash toolkit from Intridea. Its Mash, Dash, Clash, and Trash, objects provide some syntactic sugar on top of Ruby’s Hash.

Thanks to Mike’s linkblog, another project has caught my eye. Virtus from Piotr Solnica extracts DataMapper’s Property API, for the times when you need to implement attributes on your objects yet maintain a bit more encapsulation. I love the module approach for defining properties:

module Name
  include Virtus

  attribute :name, String
end

module Age
  include Virtus

  attribute :age, Integer
end

class User
  include Name, Age
end

user = User.new(:name => 'John', :age => '30')

Check the excellent README or source on GitHub for more.

t – Powerful command line interface for Twitter #

As regular listeners know, I love Earthquake, the super awesome text mode Twitter client from jugyo (十行). What Earthquake is to the streaming API, t from Erik Michaels-Ober is to REST API in the command line. Erik and I have helped maintain John Nunemaker’s Twitter gem for a few years now. While John included a basic command line interface early on, it never approached the level of Unix-y sophistication as Erik has created.

T supports a massive list of commands and subcommands including anything you’d expect in a Twitter client, but the real power is in piping commands together, Unix style:

Favorite the last 10 tweets that mention you:

t mentions -n 10 -l | awk '{print $1}' | xargs t favorite

Count the number of employees who work for Twitter:

t list members twitter team | wc -l

Add everyone you’re following to that list (up to 500 users):

t followings | xargs t list add following-`date "+%Y-%m-%d"

Check out the README for installation and usage.

noexec – Run Ruby scripts without bundle exec #

We’ve covered a few of Josh Hull’s projects on this blog. His latest is so simple, yet quite useful. If you use Bundler, you probably spend a good part of your day running bundle exec. I even use a zsh alias be for this purpose. Well now, we can stop.

With noexec, Josh has created a small script that will walk up your directory structure until it can find a Gemfile. If the executable you’re running is in that Gemfile, it will use it instead of Bundle.setup.

Simply install the gem:

gem install noexec

… and be sure to export the following environment variable in your shell profile:

RUBYOPT="-r`noexec`"

Check the source on GitHub for more.

OmniAuth goes 1.0 #

OmniAuth, everyone’s favorite multi authentication provider released version 1.0 this week. As Michael outlines in the official blog post, the biggest changes are:

  • Authentication strategies are no longer in OmniAuth core, but reside in their own gems. This means there is no gatekeeper for implementing a strategy for a given service.
  • A basic bare-bones identity strategy in the form of omniauth-identity
  • Improved dynamic strategies with support for custom forms.

Check out the wiki and blog post for more.

Episode 0.5.9 – Ruby gems with Nick Quaranto

Wynn sat down with Nick Quaranto at Red Dirt Ruby Conference to talk about Gemcutter, RubyGems.org, and how to get started creating your own Ruby gem. Items mentioned in the show: Nick Quaranto, creator of Gemcutter which is now RubyGems.org Gemcutter is the Ruby community’s gem hosting service. Tom Preston-Warner, founder of GitHub RubyForge was […]

Summer Breeze: creates dynamic Rails fixtures for Jasmine tests #

On stage at Red Dirt Ruby Conference, Noel Rappin has released Summer Breeze, a gem that makes working with Jasmine in Rails a bit easier. Summer Breeze dynamically creates Rails fixtures for your Jasmine tests.

Installation and usage

To install via RubyGems:

gem install summer_breeze

… and run the bundled generator:

rails generate summer_breeze:install

Now you can define you fixtures in the generated initializer:

fixture "PostsController##index.body_container"

You then have several options for telling Jasmine about your new
fixture:

sb.loadFixture(fixture_name)
sb.findSelector(fixture_name, selector)
sb.readFixture(fixture_name)

A sample test might look like:

it("hides text when asked", function() {
  $form_container = sb.findSelector('login', '.form_container');
  toggle_handlers.init();
  $hide_link = $form_container.find(".toggle_link");
  expect($hide_link).not.toHaveClass("hidden");
  $hide_link.click();
  expect($hide_link).toHaveClass("hidden");
});

Be sure and check the
Readme for advanced
usage and limitations.

[Source on GitHub]

teamocil: Ruby and YAML-powered terminal layout manager for tmux #

It’s a bit ironic that as a UX developer I spend most of my time in the terminal. That’s why I’m always on the lookout for new tools that improve my command line user experience.

My latest find is Teamocil a nice Ruby gem from Rémi Prévost that manages your tmux layouts. For those new to tmux:

tmux is a terminal multiplexer: it enables a number of terminals (or windows), each running a separate program, to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached.

Here’s a quick look at a simple Teamocil and tmux layout in action:

Screencap

To set up your own tmux session, you’ll need to install it via your favorite package manager. On the Mac, I use Homebrew.

brew install tmux

Next, you’ll need the Teamocil gem:

gem install teamocil

Now we need to set up our layout:

mkdir ~/.teamocil
touch ~/.teamocil/styles.yml

Here’s my quick 50-50 split example from the screenshot:

thechangelog » cat ~/.teamocil/styles.yml                          ~/Blogs/thechangelog  
windows:
  - name: prototype
    splits:
      - cmd: cd ~/hp/code/styles
      - cmd:
        - cd ~/hp/code/styles
        - serve
        width: 50%

Now we just run tmux and teamocil:

$ tmux
$ teamocil styles

Be sure and check the Readme for more info or how to create vertically split layouts, too.

[Source on GitHub]

hitch: Git author attribution helper for pair programmers #

Pair programming is like flying F-14s, and not just because our profession enjoys the same rock star status. Just like Maverick and Goose, one dev flies, and one is pretty much the Radar Intercept Officer, having a more dedicated view of threats including syntax errors and stray whitespace.

But just like there are two names on those Top Gun plaques, there are two devs in a pair, so there shouldn’t there be two names on the Git commit? After all “We happened to see a MiG 28 do a 4g negative dive.”

Going steady with your pair? Time to get hitched

Hitch from Rogelio J. Samour, Ruby hacker, bass player, Vim aficionado, and Solutions Barista at Hashrocket has created an easy way to assign multiple author attribution for your Git commits. Hitch creates a unique pair from Git users and even persists those pairs between terminal sessions. Pairs can even have their own fancy Gravatar for sites that support it (like GitHub).

Begin by installing the Ruby gem:

gem install hitch

RVM users will need to install the Hitch gem across all of their gemsets by running:

for x in $(rvm list strings); do rvm use $x@global && gem install hitch; done

Finally, Hitch needs some aliases in your Bash or Zsh profile:

hitch --setup >> ~/.bashrc

or

hitch --setup >> ~/.zshrc

You can then ‘hitch’ users together with hitch

$ hitch pengwynn adamstac

I don't know who pengwynn is.
Do you want to add pengwynn to ~/.hitch_pairs?
$ y

What is pengwynn's full name?

$ Wynn Netherland
I don't know who adamstac is.

$ y
What is adamstac's full name?

$ Adam Stacoviak
What is the group email? e.g. dev@hashrocket.com will become dev+therubymug+leshill@hashrocket.com

$ ping@thechangelog.com
Adam Stacoviak and Wynn Netherland <ping+adamstac+pengwynn@thechangelog.com>

This ‘new’ email address still gets routed to the same ‘ping’ address in gmail, so no new email setup needed. Now we can set up this new email address on Gravatar:

email screen cap

There you have it. What tools do you use in your pair programming workflow? Let us know, we’d love to share them with our readers.

Check out the source on GitHub.

govkit: Open Government APIs in a box #

In the same way that Fog aims to be the “Ruby cloud services library” by providing an all-in-one bundle of wrappers for popular cloud services including Amazon, Rackspace, and others, GovKit from OpenGovernment is a Swiss Army Knife of government API wrappers. GovKit currently supports:

You’ll need to grab API keys for each service you want use. If you’re running Rails, GovKit includes a handy generator for creating an initializer to hold your config info in config/initializers/govkit.rb:

rails generate govkit

[Source on GitHub]

vain: Check GitHub user stats from the command line #

With a name reminiscent of Ego, the at-a-glance traffic/followers/subscribers checker for iPad and iPhone, comes vain, the GitHub followers/watchers/forks checker for the command line from John Crepezzi.

Vain is distributed as a Ruby gem:

gem install vain

You can then get the skinny on any GitHub user with vain <username>. Normally we include example terminal output in a <code> block on this blog, but since vain has such great terminal color support, a screenshot is in order:

Screenshot

You might know John from his excellent ice_cube gem, an amazing recurring date library for Ruby that supports iCal, YAML, and English.

[Source on GitHub] [Comment on Hacker News]

A pair of gems to create and expand goo.gl URLs #

Now that Google has released an API for its goo.gl URL shortening service, command line geeks have a couple of options to create short URLs without opening a browser.

google_url_shortener

Developed by Josh Nesbitt at Stac, google_url_shortener is a handy command line utility to create and expand goo.gl URLs.

Install via Rubygems

gem install google_url_shortener

… and configure your API key

googl install supercalifragilisticexpialidocious

Now you can shorten URLS with

$ googl shorten http://thechangelog.com                                         
--> http://goo.gl/qWxv

The built-in help shows the full usage:

~ » googl --help                                                                 
Google URL Shortener

Examples:

  googl install myapikey
  googl {shorten,s} http://example.com
  googl {expand,e} http://goo.gl/1234
  googl expand http://goo.gl/1234 -a

Options:
  --analytics, -a:   Show analytics when expanding a URL
    --version, -v:   Print version and exit
       --help, -h:   Show this message

Be sure and check out the Stac blog post for tips on setting up copy-to-the-clipboard Bash aliases and such.

Get Shortly

If, like us here at The Changelog, your needs for URL shortening go beyond goo.gl, you might check out Shortly from Bagwan Pankaj. In addition to goo.gl, Shortly also supports bit.ly, is.gd, and tinyurl.com.

If someone wanted to beat me to it and fork the project to add ShortSwitch support for our lg.gd domain, you just might get some ink on this here blog…

[google_url_shortener on GitHub] [shortly on GitHub]

betabuilder: Ruby gem makes iOS ad-hoc builds suck less #

Behind most every App Store download, there is a painful trail of ad hoc beta builds as developers send beta bits to users to gather feedback and fix bugs. Luke Redpath, UK Rubyist and iOS developer, aims to ease that pain for iOS developers with BetaBuilder, a Ruby gem that bundles up a collection of rake tasks to make it easier to deploy your iOS apps.

BetaBuilder supports distributing your apps own your own server or using TestFlightApp.com. To get started, first install the gem:

gem install betabuilder

Next, require BetaBuilder in your Rakefile:

require 'rubygems'
require 'betabuilder'

… and configure your app:

BetaBuilder::Tasks.new do |config|
  # your Xcode target name
  config.target = "MyGreatApp"

  # the Xcode configuration profile
  config.configuration = "Adhoc" 

  config.deploy_using(:web) do |web|
    web.deploy_to = "http://beta.myserver.co.uk/myapp"
    web.remote_host = "myserver.com"
    web.remote_directory = "/remote/path/to/deployment/directory"
  end
end

Now we can see all of our tasks with rake -T:

rake beta:archive   # Build and archive the app
rake beta:build     # Build the beta release of the app
rake beta:deploy    # Deploy the beta using your chosen deployment strategy
rake beta:package   # Package the beta release as an IPA file
rake beta:prepare   # Prepare your app for deployment
rake beta:redeploy  # Deploy the last build

If you want to use TestFlight instead of hosting your builds yourself, simply swap out the deploy config with:

config.deploy_using(:testflight) do |tf|
  tf.api_token  = "YOUR_API_TOKEN"
  tf.team_token = "YOUR_TEAM_TOKEN"
end

Nifty. Need additional deploy strategies? Go ahead and fork the project and share it with the community.

[Update]:

Thanks, Luke, for pointing out some prior art from Hunter who lent the name to the project.

[Source on GitHub]

rawler: Crawl your website and find broken links with Ruby #

Need a quick-and-dirty way to find broken links on your web site? Rawler from Oscar Del Ben is a Ruby gem that gives you a command line tool to crawl your site, looking for errors.

Install via Rubygems:

gem install rawler

For usage, just execute the command rawler --help:

~ » rawler --help                                                                ~ 255 ↵ 
Rawler is a command line utility for parsing links on a website

Usage:
      rawler http://example.com [options]

where [options] are:
  --username, -u <s>:   HTT Basic Username
  --password, -p <s>:   HTT Basic Password
       --version, -v:   Print version and exit
          --help, -h:   Show this message

Point Rawler to your URL and you’ll get a list of followed links and their HTTP status codes:

~ » rawler http://thechangelog.com                                               ~ 130 ↵ 
301 - http://thechangelog.com/episodes
200 - http://thechangelog.com/archive
200 - http://thechangelog.com/
200 - https://chrome.google.com/extensions/detail/oiaejidbmkiecgbjeifoejpgmdaleoha
301 - http://github.com
200 - http://stylebot.me
200 - http://twitter.com/stylebot
200 - http://thechangelog.com/tagged/css
200 - https://github.com/handlino/CompassApp

...

The roadmap includes:

  • Follow redirects, but still inform about them
  • Respect robots.txt
  • Export to html

If you want to help out, fork the project and contribute.

[Source on GitHub]

Episode 0.4.4 – Ruby 1.9, Nokogiri, and tender lovemaking with Aaron Patterson

Wynn caught up with Aaron Patterson, aka @tenderlove, to talk about Ruby 1.9, Nokogiri, and muscle cars. Items mentioned in the show: RubyCommitters.org lists all the folks who hack on the Ruby language Nokogiri is a library for parsing XML and HTML The origins of tenderlove, Aaron’s online persona Hot linking, check it and see. […]

grape: a Ruby DSL for making APIs #

If you’re writing a web service and you’d like to expose an API to the world, few things are simpler than running a Sinatra application to provide one. Grape, by Michael Bleigh, is one of those things. Grape builds on top of rack, but gives you versioning, automatically providing responses in multiple formats, and other cool stuff.

Here’s a tiny example for FooCorp, who wants to expose their paradigm-shifting, revolutionary Widget models to the world:

class Foo::API < Grape::API
  version '2'

  resource :widgets do

    get :best do
      Widget.best_list
    end

    get '/show/:id' do
      Widget.find params[:id]
    end

  end
end

Since this is just another Rack application, you’d put this into your config.ru:

run Foo::API

This gives you these two calls:

  • /2/widgets/best(.json)
  • /2/widgets/show/:id(.json)

I originally thought that Rails 3 did just about as much as they possibly could to eliminate extra noise with the new respond_with syntax, but it’s still more than Grape. Here’s what a similar Rails 3 controller would look like:

class WidgetController < ApplicationController
  respond_to :html, :json

  def show
    respond_with(Widget.find(params[:id]))
  end

  def best
    respond_with(Widget.best_list)
  end
end

This also doesn’t take into account the versioning aspect, either. Now, Rails obviously can do a bit more than Grape can, but APIs are a great reason to use a microframework: You want the web server to be doing as little work as possible with an API. Serving up some JSON is a much more lightweight activity than the big, JavaScript-heavy pages that we expect from the Web today.

Grape’s roadmap shows some cool stuff is still in store. Rate Limiting is an important feature for any API, and filter support and OAuth are nice to have.

[Source on GitHub] [RDoc] [Presentation from RubyConf 2010]

multi_xml: Flexible and fast XML parsing in Ruby #

An overlooked part of writing a good API wrapper is picking the right parsing library. It’s often a choice between speed and complex platform dependencies. Gems like MultiJSON from Intridea are valuable in providing a common interface to swappable JSON parsers, letting users of your library choose the best fit for their application.

Erik Michaels-Ober took inspiration from MultiJSON and has released MultiXML which aims to bring the swappable parsing approach to XML documents. It looks for the “best” library to use based on parsing speed, looking first for LibXML, then Nokogiri, then Hpricot, and finally REXML. Of course, you can specify your own library of choice.

You can install MultXML via RubyGems:

gem install multi_xml

Then just require it and parse some XML:

require 'multi_xml'

MultiXml.parse('<tag>This is the contents</tag>') # parsed using LibXML if you got it

Or we can specify our library:

MultiXml.engine = :nokogiri
MultiXml.parse('<tag>This is the contents</tag>') # parsed using Nokogiri if you got it

You can set the engine via symbol or class:

MultiXml.engine = :rexml

# or

MultiXML.engine = MultiJson::Engines::Rexml

MultiXML was just released this morning so if you have ideas to add, fork away.

[Source on GitHub]

WatchWednesday for 20100929

It’s Wednesday again, time for us to serve up another quick list of projects to watch on GitHub. These are projects you might have missed or should could keep an eye on. Heroku::Autoscale David Dollar makes automatically scaling your Heroku dynos a snap with this gem. Simply add the gem to your Gemfile gem ‘heroku-autoscale’ […]

oauth2_provider: Make your Rails app an OAuth v2.0 provider #

With the likes of Facebook, GitHub, Gowalla, and others adopting OAuth 2.0, client libraries have been popping up everywhere.

If you want to join the cool kids and OAuth2-enable your API, where do you start? ThoughtWorks Studios has released oauth2_provider, a Rails plugin to provide OAuth2 authentication to your app.

Install via RubyGems:

$ gem install oauth2_provider

… and configure via Bundler.

Next, run the supplied generator to create the initializer and migrations:

$ ./script/generate oauth2_provider

Enable OAuth support alongside your regular authentication in your ApplicationController:

class ApplicationController < ActionController::Base

  # the host application's authentication filter
  before_filter :login_required

  # include Oauth2::Provider::ApplicationControllerMethods
  include Oauth2::Provider::ApplicationControllerMethods

  # this checks whether the user is logged in for purposes
  # of an authentication filter. obviously, your host application
  # will have very different code than this.  this example is
  # pulled from the sample host application with which the plugin ships.
  def login_required
    current_user_id = session[:user_id]
    if current_user_id
      User.current = User.new(current_user_id)
    else
      raise "Lack of rights!"
    end
  end

  # required by the OAuth plugin to figure out the currently logged in user
  # must be a string representation of the user.
  # A 'username', 'email' or a db primary key are good candidates.
  protected def current_user_id_for_oauth
    super
  end

  def login_required_with_oauth
    if user_id = self.user_id_for_oauth_access_token
      session[:user_id] = user_id
    elsif looks_like_oauth_request?
      render :text => "Denied!", :status => :unauthorized
    else
      login_required_without_oauth
    end
  end
  alias_method_chain :login_required, :oauth

end

By default, controller actions are not OAuth’d, so you have to opt-in, perhaps with a intermediate controller class:

class ProtectedResourceController < ApplicationController

  # Supported options are:
  #  :only => [:oauth_protected_action...]
  #  :except => [:oauth_unprotected_action...]
  # If no options are specified, defaults to oauth for all actions
  oauth_allowed :only => :index

  def index
    render :text => "current user is #{current_user.email}"
  end

  def no_oauth_here
    render :text => "this content not available via Oauth"
  end

end

[Source on GitHub]

ACLatraz: Redis-powered access control for your ruby apps #

Authentication options get a lot of press these days, but there is another Auth that can still be a pain: Authorization. ACLatraz from Kriss Kowalik caught our eye because it’s inspired by *nix Access Control Lists (ACLs), powered by Redis, and has a sense of humor.

Install ACLatraz via Ruby gems

gem install aclatraz

and configure your Redis-based storage

Aclatraz.init :redis, "redis://localhost:6379/0"

Everyone is a Suspect

In keeping with the Alcatraz theme, actors in your authorization system are deemed Suspects:

class Account < ActiveRecord::Base
  include Aclatraz::Suspect
end

ACLatraz supports global, class-related, and object-related roles:

# global admin role
@account.roles.assign(:admin) # or ...
@account.is.admin!

# Page class-related role
@account.roles.assign(:responsible, Page) # or...
@account.is.responsible_for!(Page)

# object-related role for page 15
@account.roles.assign(:author, Page.find(15)) # or...
@account.is.author_of!(Page.find(15))

Once, assigned you can interrogate your suspects a couple of ways using has?

@account.roles.has?(:admin)                # => true
@account.roles.has?(:responsible, Page)     # => true
@account.roles.has?(:author, Page.find(15) # => true

… or the more natural semantic shortcuts:

@account.is_not.admin?                      # => false
@account.is_not.responsible_for?(Page)       # => false

Guarding The Rock

To enable access control on an object, include the Aclatraz::Guard module:

class Page
  include Aclatraz::Guard

  suspects :account do
    deny all # notice that it's a method, not symbol
    allow :admin
  end
end

Check the README for even more features including custom actions, aliases, and class inheritance.

[Source on GitHub]