January 26, 2012

Rails Assets Pipeline Survival Guide

Filed under: Uncategorized — Tags: , , , , — yasi8h @ 1:50 am

Helpful settings

If you have assets pipeline enabled. By default you need to precompile your assets every time you change something (in production env). Having everything precompiled is cool but this will ask rails compile any assets that are not already compiled.

# Don't fallback to assets pipeline if a precompiled asset is missed
 config.assets.compile = true

Page Specific JS/CSS

If you want some JS/CSS to only be included in a specific set of pages.

  • break the page specific JS/CSS code to different files (ex:- profiles.js)
  • make sure they are not referenced in your manifest file (application.js)
  • add the following code snippets to the necessary files
application.html.erb (your main template)
 <%= stylesheet_link_tag "application" %>
 <%= javascript_include_tag "application" %>
 <%= yield :head %>
 <%= csrf_meta_tags %>
specific_page.html.erb (the template where you want your JS to appear)
<% content_for :head do %>
 <%= javascript_include_tag "profiles" %>
<% end %>


# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
 config.assets.precompile += %w( profiles.js )

Deploying with Capistrano

This is easy enough

load 'deploy/assets'

If you ever run across this problem:

# Disable warning message about missing dirs 'public/[javascripts|images|stylesheets]'
# src:
set :normalize_asset_timestamps, false

June 30, 2011

Fixing foursquare2 gem: NameError: uninitialized constant MultiJson

Filed under: Uncategorized — Tags: , , , — yasi8h @ 12:00 pm

If you get a error similar to the one bellow when you try to use (perform a simple task such as get a venue) from the foursquare2 gem. You are probably missing the multi_json gem.

NameError: uninitialized constant MultiJson
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday_middleware-0.6.5/lib/faraday/response/parse_json.rb:16:in `parse’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/response.rb:17:in `on_complete’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/response.rb:9:in `block in call’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/response.rb:62:in `on_complete’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/response.rb:8:in `call’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/response.rb:8:in `call’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/adapter/net_http.rb:63:in `call’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/request.rb:88:in `run’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/request.rb:28:in `run’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/connection.rb:170:in `run_request’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/faraday-0.6.1/lib/faraday/connection.rb:64:in `get’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/foursquare2-1.1.0/lib/foursquare2/venues.rb:9:in `venue’
from (irb):6
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/railties-3.0.7/lib/rails/commands/console.rb:44:in `start’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/railties-3.0.7/lib/rails/commands/console.rb:8:in `start’
from /Users/jamesx/.rvm/gems/ruby-1.9.2-p180@snipwits3/gems/railties-3.0.7/lib/rails/commands.rb:23:in `’
from script/rails:6:in `require’
from script/rails:6:in `’ruby-1.9.2-p180 :007 >

So to fix it, just add gem ‘multi_json’ to your Gemfile.

May 17, 2011

My RedDotRubyConf Experience

Filed under: Uncategorized — Tags: , — yasi8h @ 7:42 am


It have been sometime since i last blogged about anything. I have a long queue of things that i want to blog about in my head and in my todo lists. However i find my self tired and distracted to do any blogging most of the time. However today i am going to write about the RedDotRubyConf that was held in Singapore on April 22nd-23rd.

As a programmer and a technology enthuastist i have attended numerous gatherings of developers and like minded people. Back in SriLanka these meet-ups were mostly related to Linux or FOSS and organized by the [LK-LUG][10]. When i moved to Singapore sometime back (as my new position was located there) i started attending a JS meet-up ([beermates.js][11]) that was held in [][12]. However i have never attended a technology conference in my life before RedDotRubyConf.

My company ([favoritemedium][13]) sponsored the tickets(thanks! [@5ooyoung][14]). Me together with two other coworkers attended the conf. It was the first time ever a Ruby related conference was organized in the south east asian region (according to many people ;)).

Speakers and Talks

I thought this was the most important thing in a conference. For a conference to be good, it should have good speakers and good talks. However my thoughts about this changed after i attended the conference.

A lot of cool (influential, popular, rich(!), smart) (and not-so-cool => agile, agile, agile, pair programming, agile, agile… 😀 just kidding!) speakers gave talks in the con(short for conference from here on). I think as a whole they were grate. You can see a full list of the Talks and the Speakers here. I am going to write about the talks that got most of my attention/’mind share’.

**These Talks Inspired Me**
– Mikel Lindsaar – Ruby can haz everyone
– Matz – The future of ruby
– Keynote – Dave Thomas, Pragmatic Programmers
– Advanced git techniques – Tom Preston-Werner, Github
– How to be awesome at rails – Ryan Bigg, RubyX

**These were Interesting**
– Agile the pivotal way – Ian McFarland, Pivotal Labs
– Deploying infrastructure with opscode chef – Robert Berger, Runa
– Houseparty, slumlord, or mogul? multi-tenancy with rails – Paul Gallagher, Evendis
– Agile in Real Life – Andras Kristof, ViKi
– Building a financial app in rails – Matt Jacobs, Thoughtsauce
– Flexible & adaptable to change: mongodb – Alex Nguyen, Vinova

I am not the kind of person who tries to learn a lot of new things from a event like this. I feel that if i have enough inspiration and desire i could learn about tech/framework/lang… X in my free time using the resources in the internet and all the helpful people that i can contact. However inspiration is not easy to come by, this event inspired me a hell of a lot!. Thats what its all about. I saw grate people who had awesome careers and contributions to the open source community. Seeing folks like that inspire me to try and do more!

The Crowd

I think the best part of the con was the awesome crowd. They were diverse and they were from different parts of the world. I met people from Singapore, Philippines, India, China, Indonesia and the US. But there were people from all over the world, specially from south east asia and Australia.

Most people i talked to were developers and most others were founders. I see this trend in lot of events. Developers attend events because they are about interesting topics and because they can meet interesting people. Founders attend events to mainly meet interesting people. Who knows may be you can meet your partner in some conference if you were a founder searching for one!

I regret that i didn’t have my ‘business cards’ ready. A lot of other people did though. I met folks from pretty interesting companies in the tech world today. I think events like these are grate to make new contacts and basically get to know interesting hackers. The more hackers that i talk to, the more inspiration i get, to be better at what i does. I felt like i have been waisting my time and energy doing nothing.

Pivotal Labs, ViKi, RubyX, Github and Others

I am grateful that the guys mentioned above and others who sponsored the conf and made it happen. I hope they got back some value out of the event. Most of the companies above talked about how they do things. As in how their developers develop software and spend their days. About doing things the agile way and pair programming. It was very interesting. I think the hacker inside me like how Github works. They seemed to be the most liberal out of the lot. However Github is a special company. So what works for them might not work for everyone else. The most interesting thing to me about Pivotal Labs was the fact that ‘all their developers goes home at 6pm’! Man if this is true… its a huge plus for folks who are working there, i guess.

The Venue and Free flowing sources of Caffeine

The conf was held in the Singapore Management University. I was pretty satisfied with the facilities provided at the venue. However it would have been grate if the corridors were air conditioned. As we spent a significant amount of time talking to folks outside.

Inside the auditorium, they were two screens which mirrored each other. This confused me sometimes. It made it hard to follow the slides as i always tend to scan both screens hoping to find something different. I think its something thats ‘wired’ in to my brain.

I have to say that the coffee was GOOD. I am not a ‘coffee person’ so to say. However the coffee at the conf was good, it had the taste and it had the kick ;). I even had some fun figuring out how to use the coffee machines (never use them before, interesting stuff). There was RedBull, Coke, Water other than coffee. And there was a lot of it almost all the time. Well done organizers! The lunch was pretty good too. I have no complaints what so ever about ‘them’ food.


I am so happy that i got a ton of stickers specially the Github ones 😉

2011 04 23 23 52 14

…and a neat (target-the-red-dot) tee! 🙂


Obviously enough, i wasn’t the only one to write about this. Here is a list some interesting links relating to the conf.

– [The Official Website][4]
– [A Comprehensive list of links by @cheeaun][2]
– [Google Group/Newsgroup for Attendees][3]
– [A Photo set on fliker][1]

I am eagerly waiting for the next RedDotRubyConf, hope to see you there!


February 14, 2011

Fixing: /irb/completion.rb:9:in `require’: no such file to load — readline (LoadError) on rvm

Filed under: Uncategorized — Tags: , , , , , — yasi8h @ 10:25 am

Got this error to in one of the staging servers:

$ rails c production

/home/jooolaesa/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/irb/completion.rb:9:in `require’: no such file to load — readline (LoadError)
from /home/jooolaesa/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/irb/completion.rb:9:in `’
from /home/jooolaesa/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.0/lib/rails/commands/console.rb:3:in `require’
from /home/jooolaesa/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.0/lib/rails/commands/console.rb:3:in `’
from /home/jooolaesa/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.0/lib/rails/commands.rb:20:in `require’
from /home/jooolaesa/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.0/lib/rails/commands.rb:20:in `’
from script/rails:6:in `require’
from script/rails:6:in `’

It will appear if your ruby installation is not compiled with readline library. The solution is to recompile it with readline. If you are using RVM to manage your ruby installations you would go about doing it like this.

rvm package install readline

rvm remove 1.9.2 # note that 1.9.2 must be replaced with whatever ruby installation that you are going to recompile with readline support

rvm install 1.9.2 –with-readline-dir=$rvm_path/usr

Thats it!


February 7, 2011

Find all (locally and remotely) available versions of a ruby gem

Filed under: Uncategorized — Tags: , — yasi8h @ 12:29 pm

This one took about 10 mins for me to find out. Shame oh shame…

If you are looking for all versions of rails thats been released and can be installed as a gem:

gem list rails -all -r

be warned that this will list all gems that have the word rails in it and all versions of them! just filter it out.

January 27, 2011

Switching Devise Mail Sender Address with the Environment

Filed under: Uncategorized — Tags: , , — yasi8h @ 7:04 am

This is something very simple that i took more than 5 minutes to find out 🙂

in file: config/initializers/devise.rb

if Rails.env.development?
config.mailer_sender = “”
elsif Rails.env.production?
config.mailer_sender = “”

Rails.env does the trick.

November 19, 2010

Rails Authorization wiht CanCan

Filed under: Uncategorized — Tags: , , — yasi8h @ 5:59 am


There are many authentication frameworks for rails. And a lot of people do use for getting basic authentication working in their apps. However most people tend to implement their own thing when it comes to authorization. I think this is because most people feel that their authorization needs are pretty simple and hence need no plugins. But when an application grows these home cooked solution may not scale well. After all why reinvent the wheel? (well i am sure that there is a time and a place where reinventing wheel is appropriate).

CanCan is a authorization framework that aims to be simple and provide you a central place to manage all your authentication logic. There are however more complex authorization frameworks out there. So if you do feel that CanCan doesn’t give you all the control you need you can do some googling.

You can get CanCan from

Defining Authorization Logic

What i like the most about CanCan is its ability to define all the authentication logic in one single class. This is called Ability.

The following is an example from ASCII Casts episode 192 about CanCan. (Yes there are some railscasts and some asciicasts about CanCan).

class Ability
include CanCan::Ability

def initialize(user)
can :read, :all

A bit more complicated example from one of the projects that i am working on right now looks like this.

class Ability
include CanCan::Ability

def initialize(user)
if user && user.role == ‘Admin’
can :manage, :all
elsif user && user.role == ‘Producer’
#can :read, :all

can [:index, :new, :create], User # can view existing users and add new users to the system

can [:show, :edit, :update, :destroy], User do |user_o| # can edit/destroy any users/producers who are associated to the current_producer’s publications
user.users_related_to_my_active_publications([“Producer”, “User”]).include? user_o

# Catch all block that authorize doing anything on the rest of the Classes
#can :manage, User
can :manage, Asset

elsif user && user.role == ‘User’
#can :read, :all
can :index, User #as the root controller of the application is set to UsersController we need to let every role into UsersController’s index action.
#however this does not mean everyone can see a list of users. Non admins will be redirected.
can [:show, :update], User do |user_o| #let users update and view their own profiles, but not others ==

# Catch all block that authorize doing anything on the rest of the Classes
can :manage, Asset
can :manage, Audio
can :read, :all

CanCan is mostly independent from any authentication framework that you may use. It is not tightly coupled with any specific frameworks. But it does depend on the controllers having a method called ‘current_user’. This method should give the currently logged in user. So when CanCan wants to authorize some action it will grab the output from current_user and pass it in to the initialize method of the ability class. Inside the initialize method you put your custom logic and tell CanCan what and what not a certain role can do. This is accomplished by using the can method. With the can method you can define access levels for user roles per models.

When you say can:read, Asset. It means that the user role concerned can access controller actions that allows reading Assets. For example listing all the assets or viewing a asset through the show action. So in any can :x, :y statement, the x tells cancan what actions should be allowed and the y tell cancan for what objects (Users, Books…etc) the x actions are allowed for.

The actions available are what you have in any scaffold generated restful controller. However for ease cancan have grouped some of them in to some ‘actions’.

def default_alias_actions
:read => [:index, :show],
:create => [:new],
:update => [:edit],

The above method is from cancan’s source code and it defines the default alias for actions. So if you pass in :read it would mean that you are authorizing the index and show actions. The :manage action would basically authorize all actions.

If you want to check for custom actions you could just use those instead of the standard rest actions. For more info look at (

You can pass in conditions to the can statements as follows (from

can :read, Project, :active => true, :user_id =>

The conditions passed in as a hash in the third argument are tested against the user object on which the authorization is performed on.

Or as a code block.

can [:show, :update], User do |user_o| #let users update and view their own profiles, but not others ==

I want to let user’s update their own profiles but not others. So i have added a small check for that inside little block that is passed in as a argument to the can method.

Now you know how to write some basic authorization rules. But before cancan can get to work. It need to be ‘plugged in’ to your controllers. So we have to call the method


in any controller on which we want out authorization rules applied. This method call will basically add a before filter that invokes the authorization. Or else you can put the authorization logic in separate controller actions, like:

def show
@article = Article.find(params[:id])
authorize! :read, @article

The above code (from would check for the given ‘abilities’ for the current_user and throw a exception if the current_user does not have needed authorization.

You can also check the authorization logic in a adhoc manner.

<% if can? :update, @issue %>
<%= link_to “Edit Issue”, edit_issue_path(@issue) %>
<% end %>

The above code would check whether the current user have the right to access the edit action of the articles controller.

Handling Authorization Exceptions

When a user tries to do something that s/he is not authorized to (and given that you are invoking the correct cancan methods to check for authorization) cancan will throw a cancan access denied exception. This generates a ugly error message. So you can handle this in way you want by catching it like the following code (from demonstrates.

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

Authorization when fetching ActiveRecord records

CanCan does support doing authorization when retrieving records, however this have some limitations. For more info look at

Drawbacks / Shortcomings

CanCan is a neat little gem. However it have its pros and cons. As for the cons i feel that its more easily used with restful controllers and not so easily with none restful controllers. This is not to say that you can’t use it with non restful controllers. I think CanCan is better suited for instances where you have some straight forward authorization work. As i have mentioned earlier in the article cancan tries to be simple and not too overly complicated. So it doesn’t have a lot of fancy features. But it does what it promises to do, and its pretty neat at it!.

October 16, 2010

Task Scheduling with Cron, RVM and Rails

Filed under: Uncategorized — Tags: , , , — yasi8h @ 4:00 am

I wanted to do something every hour in my rails app. Basically a scheduled task. So i looked around and there were some plugins. But i choose to go with plain old cron. This should be a very straight forward task. However there are some pitfalls to be aware of. Specially if you are using RVM which depends on some environmental variables that are set on the shell. I created a bash script that is called from corn as scheduled. If you do the same be sure to make the script executable. chmod +x

my crontab -e looks like this

# m h dom mon dow command
0,30 05-07 * * * /home/foobar/script task1
0,10,20,30,40,50 08-18 * * * /home/foobar/script task1
0,30 19-21 * * * /home/foobar/script task1
0,30 19-21 * * * /home/foobar/script task2
#clean up the logs # once a week every saturday, at 00:00 (midnight)
0 0 * * 6 /home/foobar/script task3

for clean code get the gist

I have scheduled three tasks here. I am calling the same script with different arguments.

The script.

Note the source statement in the beginning. This loads RVM. And i am using the rails runner to call the methods i want to. These are located in some model classes within my rails app. Using the runner is just one option, but there are many you can use. Take look at here for more information on this topic.
If you are interested in using a gem to do the scheduling for you. Take a look at this.
After writing this i found some more post on the net that shows some what more elegant and better ways of doing the same thing. I think you should definitely give them a read.

September 28, 2010

Installing rvm/ruby 1.9/mysql2/passenger on CentOS 5.3

Filed under: Uncategorized — Tags: , — yasi8h @ 2:40 am

Things will get a lot easier if you add some custom repos to your installation like

* Install git (sudo yum install git)
* Install curl (sudo yum install curl)
* If you want to install ruby 1.9 through rvm (meaning if you want to compile it by source) you need to install a newer version of autoconf (something thats higher than 2.6 where as CentOS 5.3 comes with 2.59).

tar xvzf autoconf-2.63.tar.gz
cd autoconf-2.63
./configure –prefix=/usr
sudo make install
cd ..


* Install rvm (follow their official instructions).
* Install 1.8.7 first. Then go on to installing 1.9 (or whatever you want to. But additional rubies might have additional dependencies like jruby -> java).

* Installing mysql (sudo yum install mysql-server mysql mysql-devel ruby-mysql)

* Install chkconfig (sudo yum install chkconfig)

* start msql on startup (sudo /sbin/chkconfig –levels 235 mysqld on from:

* Install the mysql2 gem (gem install mysql2)

* Install apache2 (sudo yum install httpd)

* Start apache on start up (sudo /sbin/chkconfig –levels 235 httpd on)

* Start apache and mysql (sudo /etc/init.d/mysql start, sudo /etc/init.d/httpd start)

* Install the needed deps for passenger (sudo yum install httpd-devel apr-devel )

* Note that you don’t actually need to install Apache Portable Runtime (APR) development headers its already there.

* Install passenger (follow the instructions on how to install passagner with rvm).

* I got a error while running apache with passenger. So to make it work i turned off selinux (look at this link on how to do that). Not ideal but it works :P.

* Done!

September 19, 2010

Notes from my First Rails 3 App

Filed under: Uncategorized — Tags: , , — yasi8h @ 12:52 pm

I just got stated with rails 3. Got in to some “not too hard to solve but takes a bit of a time to figure out a fix” type of issues. This post is a account of the problems and the solutions/work arounds i applied.

Notes on installing/using Mysql2

undefined method `errno’ for #Mysql2::Error:0x00000100ff0c98

On running rake db:create if you get a error such as:

undefined method `errno' for #Mysql2::Error:0x00000100ff0c98

this is a bug. Use the latest version of mysql2 adapter by adding this line to your Gemfile

gem 'mysql2', :git => ''

then it should be fine.


“Can’t connect to local MySQL server through socket ‘/opt/local/var/run/mysql5/mysqld.sock’ (2)”

If you get “Can’t connect to local MySQL server through socket ‘/opt/local/var/run/mysql5/mysqld.sock’ (2)” execute: locate mysql.sock and use the result in place of “socket: /Applications/MAMP/tmp/mysql/mysql.sock” which was where mysql.sock was located in my mac

socket: /Applications/MAMP/tmp/mysql/mysql.sock

Notes on installing Paperclip

make sure you have imagemagick installed

Notes on Using rails-ckeditor with rails3

If you get a error such as

NameError (uninitialized constant Ckeditor::Utils):

Then you need to patch rails-ckeditor


Older Posts »

Blog at