Recursive custom to_json in Ruby for arrays of objects or nested objects

Let’s say we want to customize the json template for an object:

class User
  def to_json
    super(:except => [:password, :password_salt, :encrypted_password,
      :last_sign_in_ip, :updated_at, :current_sign_in_ip,
      :remember_token, :reset_password_token, :remember_created_at])
  end
end

Apparently this is fixed in Ruby 1.9 but for now only converting an object directly to custom json works:

@user = User.first
@user.to_json
# works fine

Cool but we want that to work for arrays:

@users = User.all
@users.to_json
# prints all attributes (does not hit our custom to_json)

And we also want custom responses in our APIs:

@users = User.all
data = {}
data[:results] = @users
data[:count] = @users.length
data.to_json
# prints all attributes (does not hit our custom to_json)

To fix this override as_json and use ActiveSupport’s encoding method. Don’t override to_json:

class User
def as_json(options)
    super(:except => [:password, :password_salt, :encrypted_password,
      :last_sign_in_ip, :updated_at, :current_sign_in_ip,
      :remember_token, :reset_password_token, :remember_created_at])
  end
end
 
...
@users = User.order_by("last_name")
      if @users
        data = {}
        data[:results] = @users
        res = data.as_json
        ActiveSupport::JSON.encode(res)
...
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , , , , , | Comments closed

Deduping join data in ruby based on multiple attributes

In the past I created an app using Rails built in HABTM and no unique index on the join tables. I’m more into the has_many :through choice today.

In order to migrate my data with a unqiue index, I had a bunch of de-duping to do. It was a bit trickier than usual because I had to de-dupe based on multiple attributes. I wrote a quick class in ruby to take of this and decided I should share it. Let me know if you have a better way. I sorta went with the fastest because I’m up against a deadline right now.

class JoinDuplicateRemover
 
  def self.de_dup
    models_dedup_hash = {
      AccountEventType => [:account_id, :event_type_id],
      ClientEventType => [:client_id, :event_type_id],
      AccountProductPackage => [:account_id, :product_package_id],
      ClientProductPackage => [:client_id, :product_package_id],
      ClientEventCountry => [:client_id, :country_id],
      ClientResearchCountry => [:client_id, :country_id],
      AccountEventCountry => [:account_id, :country_id],
      AccountResearchCountry => [:account_id, :country_id]
    }
 
    models_dedup_hash.each do |klass,scope_attrs|
 
      puts "\nStart de-duping #{klass.to_s} - #{Time.now}"
      rows_to_del = []
      index = 0
 
      klass.all.each do |instance|
 
        index += 1
        if index % 10 == 0
          print "."
          STDOUT.flush
        end
 
        conditions_hash = Hash.new
        scope_attrs.each do |sa|
          conditions_hash[sa] = instance.send(sa)
        end
        klass.where(conditions_hash).each_with_index do |dupl,i|
          rows_to_del << dupl.id unless i == 0 or rows_to_del.include?(dupl.id) 
        end
      end
 
      rows_to_del.each do |dupl|
        instance = klass.find(dupl)
        puts "Destroying: #{instance.inspect}"
        instance.destroy
      end
 
      puts "\nFinished de-duping #{klass.to_s} - #{Time.now}"
    end
  end
 
end
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , , , , , | Comments closed

More cool stuff with ruby’s tap method

I had to write up a quick data processor at work today and I wanted a decent output at the end of execution. The ruby tap method came in handy here.

class AssetDeliveryPopulater
 
  def self.populate
    results_text = []
    asset_secrets_count, asset_delivery_count, asset_not_found_count, asset_delivery_creation_errors = 0,0,0,0
 
    Email.all.tap{|emails| results_text << "#{emails.length} emails parsed." }.each do |e|
      next unless e.body
 
      asset_secrets = extract_asset_secrets_from_text(e.body)
      next unless asset_secrets
 
      asset_secrets.tap{|as| asset_secrets_count += as.length}.each do |asset_secret|
        if a = Asset.find_by_secret(asset_secret)
          if ad = AssetDelivery.create(
              :asset => a,
              :campaign => e.campaign,
              :client => e.client,
              :created_at => e.created_at
            )
            asset_delivery_count += 1
            puts "Recorded an asset delivery: #{ad.inspect}"
          else
            asset_delivery_creation_errors += 1
            puts "Could not record the delivery: #{ad.errors.inspect}"
          end
        else
          asset_not_found_count += 1
          puts "Could not find asset with secret #{asset_secret}"
        end
      end
    end
 
    results_text << "#{asset_secrets_count} asset secrets found."
    results_text << "#{asset_delivery_count} asset deliveries recorded."
    results_text << "#{asset_not_found_count} assets not found."
    results_text << "#{asset_delivery_creation_errors} asset delivery records not created due to errors."
    puts results_text.join("\n")
  end
 
  # Given some text, extract secret asset hashes and return an array
  def self.extract_asset_secrets_from_text(text)
    text.scan(/http:\/\/[^'\/]+\/products\/([^'\/]+)/).first
  end
end
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , | Comments closed

Tap before you squash

Tap is a pretty awesome ruby method I recently discovered.

Let’s say I have the following request:

post  '/api/v1/users/', 
          params.merge(:sig => 
             Authentication.calculate(TestAuthData.secret_access_key,params.to_query)
          ).to_json

I realize something is screwed and I want to print out the sig before sending. Normally I would actually rewrite my code:

sig = Authentication.calculate(TestAuthData.secret_access_key,params.to_query)
puts "sig = #{sig}"
post  '/api/v1/users/', params.merge(:sig => sig).to_json

That’s a bit annoying. With tap I can just do this:

post  '/api/v1/users/', 
          params.merge(:sig => 
            Authentication.calculate(TestAuthData.secret_access_key,params.to_query).tap{|s| puts "sig = #{s}"}
          ).to_json
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , , | Comments closed

RSpec 2, Sinatra and Mongoid example

I spent yesterday coding a very abbreviated version of an authentication service that uses Sinatra, Mongoid and RSpec 2. It took more than a couple hours because there are so many outdated code samples on the web that just don’t work. I put my code up on github for people to see. Just clone the repository and run:

rake spec

While the current example is very basic, I will update it with enhancements and talk more about how to write a good authentication service. For this example I quickly rolled my own basic authentication since the main purpose is to get you up and running quickly with Sinatra, Mongoid, and RSpec2 . I may end up using Authlogic, Devise, or improving on my own authentication functionality.

Get the code here.

Feel free to contribute to the example. Keep in mind this is a service to be consumed by front end apps, not a full application. Also I won’t accept contributions without tests.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , , , , , | Comments closed

Rails Authentication with Devise and CanCan part 2 – Restful Resources for Administrators

About two months ago I wrote an article on getting started with Devise and CanCan. Since then, I’ve implemented the Devise + CanCan combo on three projects and wrote a couple specs for Ryan Bates to help improve CanCan functionality. This article will focus more on Devise with some CanCan sprinkled in there.

If you read my first article on Devise + CanCan, you have some questions on your mind. The most common question was how to create a RESTful interface for a super admin to CRUD users. This is a common requirement for managing users and/or keeping registration private. This is really easy.

I’m going to show you how to keep the awesome functionality provided by Devise while adding your custom stuff with no major time cost!

Adding custom functionality to a Devise enabled model is easy

Step 1 – Configure Routes
Since you probably want to keep your public interface for logging in and password recovery, leave your devise routes and add RESTful routes for users:

devise_for :users
resources :users

Step 2 – The User Controller
Next you need to set up your CRUD actions in the controller. Most of the actions are typical:

class UsersController < ApplicationController
  before_filter :get_user, :only => [:index,:new,:edit]
  before_filter :accessible_roles, :only => [:new, :edit, :show, :update, :create]
  load_and_authorize_resource :only => [:show,:new,:destroy,:edit,:update]
 
  # GET /users
  # GET /users.xml                                                
  # GET /users.json                                       HTML and AJAX
  #-----------------------------------------------------------------------
  def index
    @users = User.accessible_by(current_ability, :index).limit(20)
    respond_to do |format|
      format.json { render :json => @users }
      format.xml  { render :xml => @users }
      format.html
    end
  end
 
  # GET /users/new
  # GET /users/new.xml                                            
  # GET /users/new.json                                    HTML AND AJAX
  #-------------------------------------------------------------------
  def new
    respond_to do |format|
      format.json { render :json => @user }   
      format.xml  { render :xml => @user }
      format.html
    end
  end
 
  # GET /users/1
  # GET /users/1.xml                                                       
  # GET /users/1.json                                     HTML AND AJAX
  #-------------------------------------------------------------------
  def show
    respond_to do |format|
      format.json { render :json => @user }
      format.xml  { render :xml => @user }
      format.html      
    end
 
  rescue ActiveRecord::RecordNotFound
    respond_to_not_found(:json, :xml, :html)
  end
 
  # GET /users/1/edit                                                      
  # GET /users/1/edit.xml                                                      
  # GET /users/1/edit.json                                HTML AND AJAX
  #-------------------------------------------------------------------
  def edit
    respond_to do |format|
      format.json { render :json => @user }   
      format.xml  { render :xml => @user }
      format.html
    end
 
  rescue ActiveRecord::RecordNotFound
    respond_to_not_found(:json, :xml, :html)
  end
 
  # DELETE /users/1     
  # DELETE /users/1.xml
  # DELETE /users/1.json                                  HTML AND AJAX
  #-------------------------------------------------------------------
  def destroy
    @user.destroy!
 
    respond_to do |format|
      format.json { respond_to_destroy(:ajax) }
      format.xml  { head :ok }
      format.html { respond_to_destroy(:html) }      
    end
 
  rescue ActiveRecord::RecordNotFound
    respond_to_not_found(:json, :xml, :html)
  end
 
  # POST /users
  # POST /users.xml         
  # POST /users.json                                      HTML AND AJAX
  #-----------------------------------------------------------------
  def create
    @user = User.new(params[:user])
 
    if @user.save
      respond_to do |format|
        format.json { render :json => @user.to_json, :status => 200 }
        format.xml  { head :ok }
        format.html { redirect_to :action => :index }
      end
    else
      respond_to do |format|
        format.json { render :text => "Could not create user", :status => :unprocessable_entity } # placeholder
        format.xml  { head :ok }
        format.html { render :action => :new, :status => :unprocessable_entity }
      end
    end
  end
  ...
end

CanCan provides the class level accessible_by method that I am using to retrieve all users that can be viewed by the current user. The load_and_authorize_resource filter provided by CanCan actually does this accessibility filtering for you to keep things DRY and it recognizes collections as of this issue fix. I support sorting in my actual code so I didn’t want to use the CanCan filter to grab my user objects in the index action.

The other two filters – get_user and accessible_roles – are pretty basic:

  # Get roles accessible by the current user
  #----------------------------------------------------
  def accessible_roles
    @accessible_roles = Role.accessible_by(current_ability,:read)
  end
 
  # Make the current user object available to views
  #----------------------------------------
  def get_user
    @current_user = current_user
  end

Finally, respond_to_not_found is an application wide helper I use to respond when a requested object is not found. I stole it from the Fat Free CRM source code.

Next we’ll look at the Update action which has some non standard code.

  # PUT /users/1
  # PUT /users/1.xml
  # PUT /users/1.json                                            HTML AND AJAX
  #----------------------------------------------------------------------------
  def update
    if params[:user][:password].blank?
      [:password,:password_confirmation,:current_password].collect{|p| params[:user].delete(p) }
    else
      @user.errors[:base] << "The password you entered is incorrect" unless @user.valid_password?(params[:user][:current_password])
    end
 
    respond_to do |format|
      if @user.errors[:base].empty? and @user.update_attributes(params[:user])
        flash[:notice] = "Your account has been updated"
        format.json { render :json => @user.to_json, :status => 200 }
        format.xml  { head :ok }
        format.html { render :action => :edit }
      else
        format.json { render :text => "Could not update user", :status => :unprocessable_entity } #placeholder
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
        format.html { render :action => :edit, :status => :unprocessable_entity }
      end
    end
 
  rescue ActiveRecord::RecordNotFound
    respond_to_not_found(:js, :xml, :html)
  end

That was easy!

The only unusual code we added is to clean up the password request params if the user’s password field is blank, and validate the password with Devise’s valid_password? method if it’s not blank. That allows us to provide a UI that looks like this:
User interface for editing a user with RESTful additions to the Rails Devise authentication gem
Step 3 – Add you views
It may seem a bit redundant to show all of my view code, but I’m going to do it anyway so you can see how I’m using CanCan everywhere.

index.html.erb

<!-- table header stuff here -->
<% @users.each do |u| %>
  <tr>
    <td><%= link_to_if(can?(:read, User), "#{u.name}", user_path(u.id)) {} %></td>
    <td><%= "#{u.email}" %></td>
    <td><%= "#{u.roles.collect{|r| r.name}}" %></td>
    <td><%= link_to_if(can?(:edit, User), image_tag("/images/edit_icon.gif"), edit_user_path(u.id)) {} %></td>
    <td><%= link_to_if(can?(:delete, u), image_tag("/images/delete_icon.gif"), u, :confirm => "Are you sure?", :method => :delete) {} %></td>
  </tr>
<% end %>

Note the heavy use of link_to_if(can?(:method, object), innerHTML, path, options) . It’s nice to only display links to those who can actually use them.

User registration – new.html.erb

<h2>Register User</h2>
 
<%= form_for(@user) do |f| %>
  <%= error_messages(@user,"Could not register user") %>
 
  <%= render :partial => 'user_fields', :locals => { :f => f } %>
 
  <p><%= f.label :password %></p>
  <p><%= f.password_field :password %></p>
 
  <p><%= f.label :password_confirmation %></p>
  <p><%= f.password_field :password_confirmation %></p>
 
  <p><%= f.submit "Register" %></p>
<% end %>

Where the partial – _user_fields.html.erb is the following:

<p><%= f.label :first_name %></p>
<p><%= f.text_field :first_name %></p>
 
<p><%= f.label :last_name %></p>
<p><%= f.text_field :last_name %></p>
 
<p><%= f.label :email %></p>
<p><%= f.text_field :email %></p>
 
<% if can? :read, Role %>
	<p><%= f.label :role %></p>
	<ul class="no-pad no-bullets">
		<%= habtm_checkboxes(@user, :role_ids, @accessible_roles, :name) %>
	</ul>
<% end %>

This is quite similar to the Devise generated views except we are not using a general “resource” object, we are specifying @user. Owning our views gives us the ability to easily add custom fields.

edit.html.erb

<h3><%= @user == @current_user ? "Your Account Settings" : "Edit User" %></h3>
 
<%= form_for(@user, :html => { :method => :put }) do |f| %>
	<%= error_messages(@user,"Could not update user") %>
	<%= render :partial => 'user_fields', :locals => { :f => f } %>
 
	<p><%= f.label :password %> <i>(leave blank if you don't want to change it)</i></p>
	<p><%= f.password_field :password %></p>
 
	<p><%= f.label :password_confirmation %></p>
	<p><%= f.password_field :password_confirmation %></p>
 
	<p><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i></p>
	<p><%= f.password_field :current_password %></p>
 
  <p><%= f.submit "Update" %></p>
<% end %>
<%= link_to "Back", :back %>

show.html.erb

<h3><%= @user.name %></h3>
 
<%= link_to_if(can?(:update,@user), "Edit", edit_user_path(@user)) %> |
<%= link_to_if(can?(:delete, @user), "Delete", user_path(@user), :confirm => "Are you sure?", :method => :delete) {} %>
 
<table class="one-column-emphasis">
	<tbody>
		<tr>
			<td class="oce-first">Email:</td>
			<td><%= @user.email %></td>
		</tr>
		<tr>
			<td class="oce-first">Role:</td>
			<td><%= @user.roles.first.name %></td>
		</tr>
	<% if can?(:see_timestamps,User) %>
		<tr>
			<td class="oce-first">Created at:</td>
			<td><%= @user.created_at %></td>
		</tr>
		<tr>
			<td class="oce-first">Last Sign In:</td>
			<td><%= @user.last_sign_in_at %></td>
		</tr>
		<tr>
			<td class="oce-first">Sign In Count:</td>
			<td><%= @user.sign_in_count %></td>
		</tr>
	<% end %>
	</tbody>
</table>

Wait…WTF is “see_timestamps” ???

This is one thing I love about CanCan – it’s easy to add arbitrary permissions. In my CanCan ability class I can have:

#------------------------------------------------
def initialize(user)
    user ||= User.new # guest user
 
    if user.role? :admin
      can :see_timestamps, User
    elsif user.role? :normal
      can :see_timestamps, User, :id => user.id
    end
end

I’ll admit that in my actual code I’m showing the timestamps to users that can? :manage, :all but you get the idea.

Between this post and my first post on Devise and CanCan, you should be rocking out.
Rockin out with Devise and CanCan ...or a fake guitar

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , , , , , , , , , | Comments closed

Rails Authentication with Devise and CanCan – Customizing Devise Controllers

I’m tired of spending loads of time creating user authentication systems with permissions or swimming against the current to customize what’s available. There’s great open source stuff out there but until now, I haven’t gotten the full package with really easy customization.

The Devise and CanCan combo for user authentication and permissions in Rails is my combo of choice.

With Devise and CanCan, you can create a customized authentication and registration process in 15 minutes, and spend another 15 minutes implementing roles and permissions.

Rails Beauty
It’s pure beauty.

Note that the code here uses Rails 3. The difference in Rails 3 and Rails 2 code for this purpose should be minimal, but please refer to the documentation for differences.

Let’s start with authentication using devise.

Step 1 – Installation

gem install devise
rails generate devise:install
rails generate devise user

Step 2 – Configuration
Configuration is super easy with Devise. Just choose which of the 11 available modules you would like to include in your authentic model (most up-to-date list here):

  1. Database Authenticatable: encrypts and stores a password in the database to validate the authenticity of an user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.
  2. Token Authenticatable: signs in an user based on an authentication token (also known as “single access token”). The token can be given both through query string or HTTP Basic Authentication.
  3. Oauthable: adds OAuth2 support
  4. Confirmable: sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
  5. Recoverable: resets the user password and sends reset instructions.
  6. Registerable: handles signing up users through a registration process, also allowing them to edit and destroy their account.
  7. Rememberable: manages generating and clearing a token for remembering the user from a saved cookie.
  8. Trackable: tracks sign in count, timestamps and IP address.
  9. Timeoutable: expires sessions that have no activity in a specified period of time.
  10. Validatable: provides validations of email and password. It’s optional and can be customized, so you’re able to define your own validations.
  11. Lockable: locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.

easy_button
I chose 5 of the 11 modules and configured with the following code:

# In your model
 class User < ActiveRecord::Base
    devise :database_authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable
end
 
# In your migration
create_table :users do |t|
    t.database_authenticatable
    t.confirmable
    t.recoverable
    t.rememberable
    t.trackable
    t.timestamps
end
 
# In your routes
devise_for :users

Step 3 – Use It!

# In your controllers
before_filter :authenticate_user!, :except => [:some_action_without_auth]
# Access Current User
def index
    @things = current_user.things
end

This simple modular approach to authentication is hot. Devise also makes it really easy for you to customize views. The out-of-the-box views are great for prototyping, but if you need more, just generate the views and edit them:

rails generate devise:views

Devise will generate all of the views it is using and place them in an app/views/devise directory. Now you have complete control over your views.

The next thing you might want to do is customize your controllers. This is a bit more tricky with devise and we’ll get to that in a minute. Right now I want to touch on permissions and then I’ll tie it all together.

Let’s consider an example where your website is in Alpha/Beta or maybe an internal tool. You want to restrict user registration to only an administrator. Enter CanCan created by Ryan Bates.

CanCan

CanCan is a great gem for implementing model permissions. The main reasons I chose CanCan are:

  • The code written to check permissions is very readable
  • The code written to declare permissions is very concise and readable
  • It keeps permission logic in a single location so it is not duplicated across controllers, views, etc.
  • Aliasing actions (read = index and show) creates more concise and readable code

Ryan Bates has a great screen cast on using CanCan here, but I do not recommend using his roles mask method (mentioned in the screen cast). It certainly works but it’s bad database design and you will feel the pain later.

After you install CanCan (instructions here), I recommend you set up a typical users HABTM roles relationship. So you end up with migrations that look like this:

class CreateRoles < ActiveRecord::Migration
  def self.up
    create_table :roles do |t|
      t.string :name
      t.timestamps
    end
  end
 
  def self.down
    drop_table :roles
  end
end
 
class UsersHaveAndBelongToManyRoles < ActiveRecord::Migration
  def self.up
    create_table :roles_users, :id => false do |t|
      t.references :role, :user
    end
  end
 
  def self.down
    drop_table :roles_users
  end
end

And your models look like this:

# User Model
class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
....
# Role model
class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

The next step is to create your Ability class that will define permissions. Mine looks like this:

class Ability
  include CanCan::Ability
 
  def initialize(user)
    user ||= User.new # guest user
 
    if user.role? :super_admin
      can :manage, :all
    elsif user.role? :product_admin
      can :manage, [Product, Asset, Issue]
    elsif user.role? :product_team
      can :read, [Product, Asset]
      # manage products, assets he owns
      can :manage, Product do |product|
        product.try(:owner) == user
      end
      can :manage, Asset do |asset|
        asset.assetable.try(:owner) == user
      end
    end
  end
end

Most of this is application specific but you can see some conveniences right away. For example, the super admin role “can manage all”. That line is saying “If the user has the super_admin role, he may perform any action on any model.” Easy enough. Also notice that the product team can “read” products and assets. This means that they can access the index or show action of either of those models. You can pass a block to the can method for more complicated permission checks, but that is beyond the scope of this post and pretty easy to figure out.

Let’s take a look at the role method. I store role names as CamelCase strings in the database but I access them with underscores which is more ruby like. The method looks like this:

def role?(role)
    return !!self.roles.find_by_name(role.to_s.camelize)
end

Tying it all together

Now let’s go back to the situation I mentioned earlier – you want to protect user registrations. This requires us to use CanCan to check for permissions but customize the Devise Registrations controller to restrict access.

One way to do this is to copy the devise controllers into your controllers directory and start customizing. That may be the best way to go and it’s certainly an obvious path, but all I want to do restrict registration. Should I really have to re-implement the registrations controller to do that? For now, I will not. It might make sense when there are more customizations. Instead I inherit from the Devise Registrations controller. Here are the steps:

Step 1 – Create the controller
$ mkdir app/controllers/users
$ touch app/controllers/users/registrations_controller.rb

Step 2 – Add the custom functionality

class Users::RegistrationsController < Devise::RegistrationsController
  before_filter :check_permissions, :only => [:new, :create, :cancel]
  skip_before_filter :require_no_authentication
 
  def check_permissions
    authorize! :create, resource
  end
end

The check permissions method is really simple. It calls the CanCan method, authorize!, and checks if the current user can create users. We use resource here because devise uses resource to refer to the model that can be authenticated. Also notice how I removed the require_no_authentication filter, a Devise filter which allows access to actions without authentication.

Step 3 – Tell your routes to go to the new controller

# replace devise_for :users with:
devise_for :users,  :controllers => { :registrations => "users/registrations" }

Step 4 – Handle the CanCan::AccessDenied exception
At this point if you hit the users/sign_up page when not logged in, you will notice that a CanCan::AccessDenied is thrown. This exception is thrown anytime permission is denied so you should customize it to your liking. I put the handler in my ApplicationController:

class ApplicationController < ActionController::Base
  ...
  rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = exception.message
    redirect_to root_url
  end
  ...
end

I realize I skipped some steps in here but this post + Devise documentation + CanCan documentation should help you set up authentication with roles and permissions very quickly. Let me know if you have any questions. Enjoy!

UPDATE

A part 2 of this post is now available

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , , , , , , , | Comments closed

Safely turn off Spotlight and remove from menu bar in OS X Snow Leopard

I don’t like the Spotlight indexing and search that is included in Mac OS X. I use Quicksilver instead but have been procrastinating turning off Spotlight.

Well I finally got around to disabling Spotlight and wanted to go about it in a safe way. I came across too many forum posts doing dangerous things to disable Spotlight. I also wanted and easy way to remove it from the menu bar. Below are aliases I added to my bash profile to conveniently enable and disable spotlight. I am not a bash scripting master, so feedback is welcome and appreciated.

Step 1 – Add aliases
Open your bash profile (location: ~/.bash_profile ) and add these lines:

alias spotlight-off='sudo mdutil -a -i off && sudo mv /System/Library/CoreServices/Search.bundle/ /System/Library/CoreServices/SearchOff.bundle/'
alias spotlight-on='sudo mdutil -a -i on && sudo mv /System/Library/CoreServices/SearchOff.bundle/ /System/Library/CoreServices/Search.bundle/'

Step 2 – Source your bash profile

source ~/.bash_profile

Step 3 – Run command
In your shell, run

$ spotlight-off

Step 4 – Restart SystemUIServer Process

$ ps aux | grep SystemUIServer.app
# take note of the PID which is the first number you will see
$ kill -HUP <insert PID here>

You could potentially restart your computer instead of performing Step 4, but that is inconvenient. Let me know if you have any comments or a nice way to include everything in one script. I didn’t have time to condense this process further.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , , , , , | Comments closed

Country Seed Data for your Rails App

Never go looking for basic country seed data again:

[
  { :name => 'Afghanistan', :iso_two_letter_code => 'AF' },
  { :name => 'Aland Islands', :iso_two_letter_code => 'AX' },
  { :name => 'Albania', :iso_two_letter_code => 'AL' },
  { :name => 'Algeria', :iso_two_letter_code => 'DZ' },
  { :name => 'American Samoa', :iso_two_letter_code => 'AS' },
  { :name => 'Andorra', :iso_two_letter_code => 'AD' },
  { :name => 'Angola', :iso_two_letter_code => 'AO' },
  { :name => 'Anguilla', :iso_two_letter_code => 'AI' },
  { :name => 'Antarctica', :iso_two_letter_code => 'AQ' },
  { :name => 'Antigua And Barbuda', :iso_two_letter_code => 'AG' },
  { :name => 'Argentina', :iso_two_letter_code => 'AR' },
  { :name => 'Armenia', :iso_two_letter_code => 'AM' },
  { :name => 'Aruba', :iso_two_letter_code => 'AW' },
  { :name => 'Australia', :iso_two_letter_code => 'AU' },
  { :name => 'Austria', :iso_two_letter_code => 'AT' },
  { :name => 'Azerbaijan', :iso_two_letter_code => 'AZ' },
  { :name => 'Bahamas', :iso_two_letter_code => 'BS' },
  { :name => 'Bahrain', :iso_two_letter_code => 'BH' },
  { :name => 'Bangladesh', :iso_two_letter_code => 'BD' },
  { :name => 'Barbados', :iso_two_letter_code => 'BB' },
  { :name => 'Belarus', :iso_two_letter_code => 'BY' },
  { :name => 'Belgium', :iso_two_letter_code => 'BE' },
  { :name => 'Belize', :iso_two_letter_code => 'BZ' },
  { :name => 'Benin', :iso_two_letter_code => 'BJ' },
  { :name => 'Bermuda', :iso_two_letter_code => 'BM' },
  { :name => 'Bhutan', :iso_two_letter_code => 'BT' },
  { :name => 'Bolivia', :iso_two_letter_code => 'BO' },
  { :name => 'Bosnia and Herzegovina', :iso_two_letter_code => 'BA' },
  { :name => 'Botswana', :iso_two_letter_code => 'BW' },
  { :name => 'Bouvet Island', :iso_two_letter_code => 'BV' },
  { :name => 'Brazil', :iso_two_letter_code => 'BR' },
  { :name => 'British Indian Ocean Territory', :iso_two_letter_code => 'IO' },
  { :name => 'Brunei Darussalam', :iso_two_letter_code => 'BN' },
  { :name => 'Bulgaria', :iso_two_letter_code => 'BG' },
  { :name => 'Burkina Faso', :iso_two_letter_code => 'BF' },
  { :name => 'Burundi', :iso_two_letter_code => 'BI' },
  { :name => 'Cambodia', :iso_two_letter_code => 'KH' },
  { :name => 'Cameroon', :iso_two_letter_code => 'CM' },
  { :name => 'Canada', :iso_two_letter_code => 'CA' },
  { :name => 'Cape Verde', :iso_two_letter_code => 'CV' },
  { :name => 'Cayman Islands', :iso_two_letter_code => 'KY' },
  { :name => 'Central African Republic', :iso_two_letter_code => 'CF' },
  { :name => 'Chad', :iso_two_letter_code => 'TD' },
  { :name => 'Chile', :iso_two_letter_code => 'CL' },
  { :name => 'China', :iso_two_letter_code => 'CN' },
  { :name => 'Christmas Island', :iso_two_letter_code => 'CX' },
  { :name => 'Cocos (Keeling) Islands', :iso_two_letter_code => 'CC' },
  { :name => 'Colombia', :iso_two_letter_code => 'CO' },
  { :name => 'Comoros', :iso_two_letter_code => 'KM' },
  { :name => 'Congo', :iso_two_letter_code => 'CG' },
  { :name => 'Congo (DRC)', :iso_two_letter_code => 'CD' },
  { :name => 'Cook Islands', :iso_two_letter_code => 'CK' },
  { :name => 'Costa Rica', :iso_two_letter_code => 'CR' },
  { :name => 'Cote d\'Ivoire', :iso_two_letter_code => 'CI' },
  { :name => 'Croatia', :iso_two_letter_code => 'HR' },
  { :name => 'Cuba', :iso_two_letter_code => 'CU' },
  { :name => 'Cyprus', :iso_two_letter_code => 'CY' },
  { :name => 'Czech Republic', :iso_two_letter_code => 'CZ' },
  { :name => 'Denmark', :iso_two_letter_code => 'DK' },
  { :name => 'Djibouti', :iso_two_letter_code => 'DJ' },
  { :name => 'Dominica', :iso_two_letter_code => 'DM' },
  { :name => 'Dominican Republic', :iso_two_letter_code => 'DO' },
  { :name => 'Ecuador', :iso_two_letter_code => 'EC' },
  { :name => 'Egypt', :iso_two_letter_code => 'EG' },
  { :name => 'El Salvador', :iso_two_letter_code => 'SV' },
  { :name => 'Equatorial Guinea', :iso_two_letter_code => 'GQ' },
  { :name => 'Eritrea', :iso_two_letter_code => 'ER' },
  { :name => 'Estonia', :iso_two_letter_code => 'EE' },
  { :name => 'Ethiopia', :iso_two_letter_code => 'ET' },
  { :name => 'Falkland Islands', :iso_two_letter_code => 'FK' },
  { :name => 'Faroe Islands', :iso_two_letter_code => 'FO' },
  { :name => 'Fiji', :iso_two_letter_code => 'FJ' },
  { :name => 'Finland', :iso_two_letter_code => 'FI' },
  { :name => 'France', :iso_two_letter_code => 'FR' },
  { :name => 'French Guiana', :iso_two_letter_code => 'GF' },
  { :name => 'French Polynesia', :iso_two_letter_code => 'PF' },
  { :name => 'French Southern Territories', :iso_two_letter_code => 'TF' },
  { :name => 'Gabon', :iso_two_letter_code => 'GA' },
  { :name => 'Gambia', :iso_two_letter_code => 'GM' },
  { :name => 'Georgia', :iso_two_letter_code => 'GE' },
  { :name => 'Germany', :iso_two_letter_code => 'DE' },
  { :name => 'Ghana', :iso_two_letter_code => 'GH' },
  { :name => 'Gibraltar', :iso_two_letter_code => 'GI' },
  { :name => 'Greece', :iso_two_letter_code => 'GR' },
  { :name => 'Greenland', :iso_two_letter_code => 'GL' },
  { :name => 'Grenada', :iso_two_letter_code => 'GD' },
  { :name => 'Guadeloupe', :iso_two_letter_code => 'GP' },
  { :name => 'Guam', :iso_two_letter_code => 'GU' },
  { :name => 'Guatemala', :iso_two_letter_code => 'GT' },
  { :name => 'Guernsey', :iso_two_letter_code => 'GG' },
  { :name => 'Guinea', :iso_two_letter_code => 'GN' },
  { :name => 'Guinea-Bissau', :iso_two_letter_code => 'GW' },
  { :name => 'Guyana', :iso_two_letter_code => 'GY' },
  { :name => 'Haiti', :iso_two_letter_code => 'HT' },
  { :name => 'Heard and McDonald Islands', :iso_two_letter_code => 'HM' },
  { :name => 'Holy See (Vatican City State)', :iso_two_letter_code => 'VA' },
  { :name => 'Honduras', :iso_two_letter_code => 'HN' },
  { :name => 'Hong Kong', :iso_two_letter_code => 'HK' },
  { :name => 'Hungary', :iso_two_letter_code => 'HU' },
  { :name => 'Iceland', :iso_two_letter_code => 'IS' },
  { :name => 'India', :iso_two_letter_code => 'IN' },
  { :name => 'Indonesia', :iso_two_letter_code => 'ID' },
  { :name => 'Iran', :iso_two_letter_code => 'IR' },
  { :name => 'Iraq', :iso_two_letter_code => 'IQ' },
  { :name => 'Ireland', :iso_two_letter_code => 'IE' },
  { :name => 'Isle of Man', :iso_two_letter_code => 'IM' },
  { :name => 'Israel', :iso_two_letter_code => 'IL' },
  { :name => 'Italy', :iso_two_letter_code => 'IT' },
  { :name => 'Jamaica', :iso_two_letter_code => 'JM' },
  { :name => 'Japan', :iso_two_letter_code => 'JP' },
  { :name => 'Jersey', :iso_two_letter_code => 'JE' },
  { :name => 'Jordan', :iso_two_letter_code => 'JO' },
  { :name => 'Kazakhstan', :iso_two_letter_code => 'KZ' },
  { :name => 'Kenya', :iso_two_letter_code => 'KE' },
  { :name => 'Kiribati', :iso_two_letter_code => 'KI' },
  { :name => 'North Korea', :iso_two_letter_code => 'KP' },
  { :name => 'South Korea', :iso_two_letter_code => 'KR' },
  { :name => 'Kuwait', :iso_two_letter_code => 'KW' },
  { :name => 'Kyrgyzstan', :iso_two_letter_code => 'KG' },
  { :name => 'Laos', :iso_two_letter_code => 'LA' },
  { :name => 'Latvia', :iso_two_letter_code => 'LV' },
  { :name => 'Lebanon', :iso_two_letter_code => 'LB' },
  { :name => 'Lesotho', :iso_two_letter_code => 'LS' },
  { :name => 'Liberia', :iso_two_letter_code => 'LR' },
  { :name => 'Libya', :iso_two_letter_code => 'LY' },
  { :name => 'Liechtenstein', :iso_two_letter_code => 'LI' },
  { :name => 'Lithuania', :iso_two_letter_code => 'LT' },
  { :name => 'Luxembourg', :iso_two_letter_code => 'LU' },
  { :name => 'Macao', :iso_two_letter_code => 'MO' },
  { :name => 'Macedonia', :iso_two_letter_code => 'MK' },
  { :name => 'Madagascar', :iso_two_letter_code => 'MG' },
  { :name => 'Malawi', :iso_two_letter_code => 'MW' },
  { :name => 'Malaysia', :iso_two_letter_code => 'MY' },
  { :name => 'Maldives', :iso_two_letter_code => 'MV' },
  { :name => 'Mali', :iso_two_letter_code => 'ML' },
  { :name => 'Malta', :iso_two_letter_code => 'MT' },
  { :name => 'Marshall Islands', :iso_two_letter_code => 'MH' },
  { :name => 'Martinique', :iso_two_letter_code => 'MQ' },
  { :name => 'Mauritania', :iso_two_letter_code => 'MR' },
  { :name => 'Mauritius', :iso_two_letter_code => 'MU' },
  { :name => 'Mayotte', :iso_two_letter_code => 'YT' },
  { :name => 'Mexico', :iso_two_letter_code => 'MX' },
  { :name => 'Micronesia', :iso_two_letter_code => 'FM' },
  { :name => 'Moldova', :iso_two_letter_code => 'MD' },
  { :name => 'Monaco', :iso_two_letter_code => 'MC' },
  { :name => 'Mongolia', :iso_two_letter_code => 'MN' },
  { :name => 'Montenegro', :iso_two_letter_code => 'ME' },
  { :name => 'Montserrat', :iso_two_letter_code => 'MS' },
  { :name => 'Morocco', :iso_two_letter_code => 'MA' },
  { :name => 'Mozambique', :iso_two_letter_code => 'MZ' },
  { :name => 'Myanmar', :iso_two_letter_code => 'MM' },
  { :name => 'Namibia', :iso_two_letter_code => 'NA' },
  { :name => 'Nauru', :iso_two_letter_code => 'NR' },
  { :name => 'Nepal', :iso_two_letter_code => 'NP' },
  { :name => 'Netherlands', :iso_two_letter_code => 'NL' },
  { :name => 'Netherlands Antilles', :iso_two_letter_code => 'AN' },
  { :name => 'New Caledonia', :iso_two_letter_code => 'NC' },
  { :name => 'New Zealand', :iso_two_letter_code => 'NZ' },
  { :name => 'Nicaragua', :iso_two_letter_code => 'NI' },
  { :name => 'Niger', :iso_two_letter_code => 'NE' },
  { :name => 'Nigeria', :iso_two_letter_code => 'NG' },
  { :name => 'Niue', :iso_two_letter_code => 'NU' },
  { :name => 'Norfolk Island', :iso_two_letter_code => 'NF' },
  { :name => 'Northern Mariana Islands', :iso_two_letter_code => 'MP' },
  { :name => 'Norway', :iso_two_letter_code => 'NO' },
  { :name => 'Oman', :iso_two_letter_code => 'OM' },
  { :name => 'Pakistan', :iso_two_letter_code => 'PK' },
  { :name => 'Palau', :iso_two_letter_code => 'PW' },
  { :name => 'Palestinian Territory', :iso_two_letter_code => 'PS' },
  { :name => 'Panama', :iso_two_letter_code => 'PA' },
  { :name => 'Papua New Guinea', :iso_two_letter_code => 'PG' },
  { :name => 'Paraguay', :iso_two_letter_code => 'PY' },
  { :name => 'Peru', :iso_two_letter_code => 'PE' },
  { :name => 'Philippines', :iso_two_letter_code => 'PH' },
  { :name => 'Pitcairn', :iso_two_letter_code => 'PN' },
  { :name => 'Poland', :iso_two_letter_code => 'PL' },
  { :name => 'Portugal', :iso_two_letter_code => 'PT' },
  { :name => 'Puerto Rico', :iso_two_letter_code => 'PR' },
  { :name => 'Qatar', :iso_two_letter_code => 'QA' },
  { :name => 'Reunion', :iso_two_letter_code => 'RE' },
  { :name => 'Romania', :iso_two_letter_code => 'RO' },
  { :name => 'Russia', :iso_two_letter_code => 'RU' },
  { :name => 'Rwanda', :iso_two_letter_code => 'RW' },
  { :name => 'Saint Barthelemy', :iso_two_letter_code => 'BL' },
  { :name => 'Saint Helena', :iso_two_letter_code => 'SH' },
  { :name => 'Saint Kitts and Nevis', :iso_two_letter_code => 'KN' },
  { :name => 'Saint Lucia', :iso_two_letter_code => 'LC' },
  { :name => 'Saint Pierre and Miquelon', :iso_two_letter_code => 'PM' },
  { :name => 'Saint Vincent and the Grenadines', :iso_two_letter_code => 'VC' },
  { :name => 'Samoa', :iso_two_letter_code => 'WS' },
  { :name => 'San Marino', :iso_two_letter_code => 'SM' },
  { :name => 'Sao Tome and Principe', :iso_two_letter_code => 'ST' },
  { :name => 'Saudi Arabia', :iso_two_letter_code => 'SA' },
  { :name => 'Senegal', :iso_two_letter_code => 'SN' },
  { :name => 'Serbia', :iso_two_letter_code => 'RS' },
  { :name => 'Seychelles', :iso_two_letter_code => 'SC' },
  { :name => 'Sierra Leone', :iso_two_letter_code => 'SL' },
  { :name => 'Singapore', :iso_two_letter_code => 'SG' },
  { :name => 'Slovakia', :iso_two_letter_code => 'SK' },
  { :name => 'Slovenia', :iso_two_letter_code => 'SI' },
  { :name => 'Solomon Islands', :iso_two_letter_code => 'SB' },
  { :name => 'Somalia', :iso_two_letter_code => 'SO' },
  { :name => 'South Africa', :iso_two_letter_code => 'ZA' },
  { :name => 'South Georgia and the South Sandwich Islands', :iso_two_letter_code => 'GS' },
  { :name => 'Spain', :iso_two_letter_code => 'ES' },
  { :name => 'Sri Lanka', :iso_two_letter_code => 'LK' },
  { :name => 'Sudan', :iso_two_letter_code => 'SD' },
  { :name => 'Surinam', :iso_two_letter_code => 'SR' },
  { :name => 'Svalbard and Jan Mayen', :iso_two_letter_code => 'SJ' },
  { :name => 'Swaziland', :iso_two_letter_code => 'SZ' },
  { :name => 'Sweden', :iso_two_letter_code => 'SE' },
  { :name => 'Switzerland', :iso_two_letter_code => 'CH' },
  { :name => 'Syria', :iso_two_letter_code => 'SY' },
  { :name => 'Taiwan', :iso_two_letter_code => 'TW' },
  { :name => 'Tajikistan', :iso_two_letter_code => 'TJ' },
  { :name => 'Tanzania', :iso_two_letter_code => 'TZ' },
  { :name => 'Thailand', :iso_two_letter_code => 'TH' },
  { :name => 'Timor-Leste', :iso_two_letter_code => 'TL' },
  { :name => 'Togo', :iso_two_letter_code => 'TG' },
  { :name => 'Tokelau', :iso_two_letter_code => 'TK' },
  { :name => 'Tonga', :iso_two_letter_code => 'TO' },
  { :name => 'Trinidad and Tobago', :iso_two_letter_code => 'TT' },
  { :name => 'Tunisia', :iso_two_letter_code => 'TN' },
  { :name => 'Turkey', :iso_two_letter_code => 'TR' },
  { :name => 'Turkmenistan', :iso_two_letter_code => 'TM' },
  { :name => 'Turks and Caicos Islands', :iso_two_letter_code => 'TC' },
  { :name => 'Tuvalu', :iso_two_letter_code => 'TV' },
  { :name => 'Uganda', :iso_two_letter_code => 'UG' },
  { :name => 'Ukraine', :iso_two_letter_code => 'UA' },
  { :name => 'UAE', :iso_two_letter_code => 'AE' },
  { :name => 'United Kingdom', :iso_two_letter_code => 'GB' },
  { :name => 'United States', :iso_two_letter_code => 'US' },
  { :name => 'United States Minor Outlying Islands', :iso_two_letter_code => 'UM' },
  { :name => 'Uruguay', :iso_two_letter_code => 'UY' },
  { :name => 'Uzbekistan', :iso_two_letter_code => 'UZ' },
  { :name => 'Vanuatu', :iso_two_letter_code => 'VU' },
  { :name => 'Venezuela', :iso_two_letter_code => 'VE' },
  { :name => 'Vietnam', :iso_two_letter_code => 'VN' },
  { :name => 'British Virgin Islands', :iso_two_letter_code => 'VG' },
  { :name => 'US Virgin Islands', :iso_two_letter_code => 'VI' },
  { :name => 'Wallis and Futuna', :iso_two_letter_code => 'WF' },
  { :name => 'Western Sahara', :iso_two_letter_code => 'EH' },
  { :name => 'Yemen', :iso_two_letter_code => 'YE' },
  { :name => 'Zambia', :iso_two_letter_code => 'ZM' },
  { :name => 'Zimbabwe', :iso_two_letter_code => 'ZW' }  
].each do |c|
  Country.find_or_create_by_name(:name => c[:name], :iso_two_letter_code => c[:iso_two_letter_code])
end

Let me know if you have any improvements, but it’s pretty much taken directly from the ISO website.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , , , | Comments closed

Simple Quarter Select – Rails plugin for Q1,Q2,Q3,Q4 selector

Have you ever wanted a select component for Quaters of the Fiscal Year (Q1,Q2,Q3,Q4)? The Simple Quarter Select Ruby on Rails plugin does it for you. It’s highly configurable and maps to the month of any datetime attribute in your model.
Simple Quarter Select screen shot
Why map the quarter to a datetime attribute?
I think the answer is obvious but for the sake of being comprehensive, I’ll list 3 questions to guide your decision:
1) How else would you store the information in your database?
2) What if some of your objects are quarterly but others are actual dates? How about semiannual?
3) How would your sort-by-date query look?

If you answer these 3 questions, you will likely see the logic in my decision.

Installation
Get it or view the source here

Usage
It’s really easy to use. Just toss this code into your view:

<%= date_select(:some_model, :some_date_attribute, {:discard_day => true, :order => [:month,:year], 
:simple_quarter_select => true}) %>

Configurability
Simple Quarter Select has a misleading name. It should really be called “Named Month Intervals” because that represents its true flexibility. To illustrate this, let’s look at an example. Let’s say you want your users to be able to choose from two halves of a year:

<%= date_select(:some_model, :some_date_attribute, {:discard_day => true, :order => [:month,:year], 
:simple_quarter_select => true, :month_interval => 6, :interval_names => ["H1","H2"]}) %>

Simple Quarter Select sample configuration screenshot
“H1″ would store as 01/01/YYYY and “H2″ would store as 07/01/YYYY.

Or maybe you just want to display the full word “Quarter” in each option:

<%= date_select(:some_model, :some_date_attribute, {:discard_day => true, :order => [:month,:year], 
:simple_quarter_select => true, :interval_names => ["Quarter 1","Quarter 2","Quarter 3","Quarter 4"]}) %>

You get the idea :)

Let me know if you find this plugin useful or find any bugs. Enjoy!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

Posted in Software | Tagged , , , , | Comments closed