Tag Archives: rails

Ember 1.0 – rise from the ashes

We have been moving our explorer2 app to use the released version of Ember (1.0) and the accompanying Ember Data (1.0.0 beta 3). There have been lots of changes to Ember Data which you can find here.

Ember changes
Ember itself has not changed too much between RC and release but here are some things we noticed

1) Refer to routes inside quotes in linkTo blocks

Previously we had

{{#linkTo post.comment comment}}{{comment.text}}{{/linkTo}} 

which is now

{{#linkTo 'post.comment' comment}}{{comment.text}}{{/linkTo}}

2) Define hasMany etc relationships as ‘async’ in models
If the child models are loaded as something like “comment_ids”:[1,2] in the server json response then

comments: DS.hasMany('comment')

should now be

comments: DS.hasMany('comment', { async: true })

3) hasMany etc relationships are now simple strings rather than referring to the model type


is now


4) controller actions now inside ‘actions hash’.
Inside your controller put your actions inside a block like this:

actions: {
  someAction: function(){},
  anotherAction: function(){}

Ember Data Changes
There are some really important Ember Data changes, here are some highlights

1) Per model adapters.

Each model can have its own adapter to find data etc. This is really useful if you create your model from ‘non-standard’ json or assign your own ids.
Here is an example from explorer2 where we grab some json from a server and create the model on the fly.

App.CompoundAdapter = DS.Adapter.extend({
  find: function(store, type, id) {
    // return a promise inside of which is the callback which either resolves with the retrieved compound data or rejects with the status
    var promise = new Ember.RSVP.Promise(function(resolve, reject){
      var searcher = new Openphacts.CompoundSearch(ldaBaseUrl, appID, appKey);
      var pathwaysSearcher = new Openphacts.PathwaySearch(ldaBaseUrl, appID, appKey);
      // get the compound details  
	  var callback=function(success, status, response){  
        if (success) {
	    var compoundResult = searcher.parseCompoundResponse(response);
            compoundResult['pathways'] = [];
        } else {
      searcher.fetchCompound('http://www.conceptwiki.org/concept/' + id, null, callback);
    return promise;

2) Promises and chaining.

Ember data makes heavy use of Promises (https://github.com/tildeio/rsvp.js). When finding models you resolve or reject from within the promise and can even chain them together if you need to do something else once you have found/created a model. The adapter example above demonstrates a simple promise. Here is an example of a promise chain where we find a model and then do something with it after it is found.

me.get('store').find('compound', url.split('/').pop()).then(function(compound) {

3) Find uses the store, not the model
Before we would have


now we have

store.find('post', 1)

Similarly when creating we do

store.createRecord('post', {title: 'a great post'})

4) onCreate, transactions gone – use promises
previously we would listen to the ‘onCreate’ action of a model and then do something with it. Now do

  //do something

5) Underscored keys needs different serializer

If your relationships are sent as underscored values in the json, for example:

{"comment":{"id":4,"text":"comment 3","post_id":1}}

Then you need to tell Ember Data by creating an ApplicationSerializer with

App.ApplicationSerializer = DS.ActiveModelSerializer.extend({});

Otherwise your json will look like

{"comment":{"id":4,"text":"comment 3",post:1}}

which in our case breaks the default rails behaviour.

6) Add child model to parent after save
Inside the promise when saving a child model you need to add it to the parent or it will not be shown when transitioning. In this example we save a comment for a post, add it to the posts array of comments and then transition to the index for that post. You could also reload the parent model instead, not sure what the preferred/correct behaviour should be.

        //post.reload(); //could do this instead

Overall, quite a lot of changes but I think they make Ember easier to use and hopefully make it stable (for a little while at least). You can find an updated simple blog app with the latest changes here. The non rails version using fixture adapter is here with jsfiddle here.

handle_asynchronously missing method with delayed job and passenger: ‘require’ needed

We use delayed job in lots of our applications to handle long running tasks but we came across a weird issue when deploying our explorer2 rails app on apache using passenger. Passenger would throw out a 500 with ‘missing method handle_ayncronously’ whenever the application was accessed. Commenting out the handle_asynchronously part in the class (one of the models) and all would work fine. Running in development all was perfect and delayed job worked without a hitch. To see if we could replicate it we created the most basic rails app possible with one model with a method that used handle_asynchronously and guess what……it did not work either. Really left us a bit stumped how to solve it until I had the idea to use require 'delayed_job' in the model class using it. Then everything worked again.
So, we have the solution but we are not really sure what the cause is. The problem occurs in ruby 1.8 or 1.9 with rails 2.3.12 or 2.3.13 and delayed job 4.0.0 or 3.0.5 (via delayed job active record). However, we have code that uses handle_asynchronously (eg the original openPHACTS gui) in the exact same way without a hitch! Anyway, I thought that bundler etc meant that ‘require’ was no longer required but be warned….

Ember JS: Ruby gem version hell

We are used to adding a gem to our Gemfile and just quietly getting on with things. However. with Ember things are not that easy. It is a moving target and you may see things like

Uncaught Error: assertion failed: Ember Handlebars requires Handlebars 1.0.0-rc.3 or greater. Include a SCRIPT tag in the HTML HEAD linking to the Handlebars file before you link to Ember.


Uncaught Error: assertion failed: Ember Views require jQuery 1.8, 1.9 or 2.0

Ember seems to have some difficulty figuring out what version numbers it can actually use: eg 1.0.0 is greater than 1.0.0.rc.3 but not to Ember. I have had to freeze handlebars-assets at 0.12.0 and jquery-rails at 2.2.1 to get round these issues. I have seen this with Ember 1.0.0.rc-6 and earlier. Be careful. One day things will hopefully get a lot simpler but until then keep your eyes open for version incompatibilities. There may be later versions of these gems that are compatible but these were versions that I know worked for me.

Update: I played around with all the gems and libraries and found that with Ember 1.0.0 rc6 you can use handlebars_assets 0.12.3. This in turn uses handlebars 1.0.0-rc.4. I also saw from the handlebars_assets github page that you can tell it to use specific versions of handlebars with

HandlebarsAssets::Config.compiler = 'my_handlebars.js' # Change the name of the compiler file
HandlebarsAssets::Config.compiler_path = Rails.root.join('app/assets/javascripts') # Change the location of the compiler file

Ember JS: Adding posts to our blog application

At the end of the last article I challenged you to add the ability to create new posts for our very simple blog application. We saw how to create new comments for a post and adding a new post uses a similar pattern. First we need a route for posts/new. Change the posts resource to include this

this.resource('posts', function() {

This means that ember will now create the routes posts, posts.index and posts.new. Previously we only had the posts route but when we go to /posts we will now transition to posts.index. We need to add a posts directory under app/javascripts/templates/ as well as handlebars files for the index and new routes.


These additional new routes means that any sub route of posts will be rendered within the posts template outlet. We need to add an {{outlet}} to it to allow this to happen. At the same time we need to move the handlebars code for showing the posts from the original posts template to the posts.index template.

The posts template now only contains


The posts.index template needs to contain the old content from the posts template

  {{#each controller}}  
    <li>{{#linkTo post this}}{{title}}{{/linkTo}}</li>

We will also add a content property to the Post model to reflect what the rails side expects.

  comments: DS.hasMany('App.Comment'),
  title: DS.attr('string'),
  content: DS.attr('string')

In hindsight using content was a poor choice since each controller has a ‘content’ propery and this could get a little confusing. However we will stick with it for the moment.

Just like in the comments.new template we need a form to submit with the details for our new post. In the posts.new template add the following

<form {{action save content on='submit'}}>
  {{view Ember.TextArea valueBinding="title" placeholder="Enter title here"}}
  {{view Ember.TextArea valueBinding="content.content" placeholder="Enter content here"}}
  <button type="submit">Create Post</button>

You can see we have content.content in the second TextArea, this is because using content alone binds to the controllers ‘content’ rather than the models.

One problem here is that ember does not know what models to use in the posts.index route. We need to tell it.

Create a PostsIndexRoute using the following code or rename the PostsRoute to PostsIndexRoute within router.js

  model: function(){
    return App.Post.find();

Add a link to post.new at the bottom of the posts.index template

{{#linkTo posts.new}}New Post{{/linkTo}}

We need to tell the PostsNewRoute how to set up the controller and we also require a controller to handle the save action. Add the following code to the router.js file.

  model: function(){
    return App.Post.createRecord();

Inside the model hook we return a new Post model to the controller. Create controllers/postsNewController.js with the following code

  save: function(post) {
    var me = this;
    post.on('didCreate', function() {

The reason we have the post.on('didCreate', function() { part is so that we do not transition to the posts.index route before the model has been saved on the server side and has an id. Otherwise we will render the page with a link to /posts/null.

NOTE 8/7/13 : I have just noticed that the post with a null id is still shown on the index page, what we need to do is change the response format for new posts and comments to stop this. In the rails side PostsController we need the create method to respond with the following { “post”: {“id”: 1, “text”: “blah”….} and similarly for the CommentsController. In the create action under if @post.save change

format.json { render :json => @post, :status => :created, :location => @post }


format.json { render :json => { :post => @post.as_json}, :status => :created, :location => @post }

Change the CommentsController create method in a similar fashion. We also need the 'didCreate' listener hook for comments save method on the ember side like we already have for the posts.

The code for this article is available here.
(Code recently updated due to ember/jquery-rails/handlebars-assets version compatibility issues and the json response format changes noted above)

Ember JS: Server side

Creating the rails app

In the Ember JS MVC tutorials we created a purely browser based application with no persistence between sessions and hard coded fixtures for data. In this article we will create a server side app to handle data persistence, we will also use it to serve our Ember application. We will use Ruby on Rails. The code is available here in zip form or if you want to fork etc on github try here. Start by creating a new rails application

rails new blog

Wait for the app to be created, go in to the blog directory and remove public/index.html. You can use ember-rails to create the ember client side skeleton code but we will do it by hand using the classes and templates we created during the MVC tutorials. I find it is helps you to understand how the application works if you use as little auto-generated code as possible. However, we will use some rails scaffold to get us started.

rails generate scaffold Post title:string content:text
rails generate scaffold Comment text:string post_id:integer

This creates the controllers, views, model, helper, db migrations etc. Then we can create the database.

rake db:migrate
rake db:create

As we defined in the MVC tutorial a Post can have many Comments so add the relationships to the rails models, in blog/app/models.

add belongs_to :post to comment model
add has_many :comments to post model

In routes we have resource for posts and comments, add a root

root :to => 'welcome#index'

We therefore need something for this route to render. Create a welcome_controller.rb in app/controllers with an index method and a index view for it in app/views/welcome/index.html.erb. The view will be empty, it is just a placeholder for our rails app to boot the root ie /. Ember will be doing all the rendering.

class WelcomeController < ApplicationController
  # GET / 
  def index 
    respond_to do |format| 
      format.html # index.html.erb 

Add the Ember application

Just like in a rails app we can make our ember application easier to manage by creating an ember app structure in app/assets/javascripts. ember-rails would do this for you.


Using the code from app.js and index.html from part 3 of the tutorial create the following files


  needs: 'post',
  text: null,
  save: function() {
    var post = this.get('controllers.post.content');
    App.Comment.createRecord({ post: post, text: this.get('text') }); 


  comments: DS.hasMany('App.Comment'),
  title: DS.attr('string')


App.Comment = DS.Model.extend({
  post: DS.belongsTo('App.Post'),
  text: DS.attr('string')

The templates directory structure mimics the data-template-name from index.html


Copy the contents of the script tags in index.html from part 3 of the MVC tutorial to the appropriate template, you do not need the enclosing script tag itself. We also need to add a router.js to the app/assets/javascript directory, use the code from app.js we created in part 3.

App.Router.map(function() {
  this.resource('post', { path: '/posts/:post_id' }, function() {
    this.resource('comments', function() {
  this.route('comment', { path: 'comments/:comment_id'});

  model: function(){
    return App.Post.find();

  model: function(params) {
    return this.modelFor('post');

  setupController: function(controller, model) {
    controller.set('text', null);

Our store.js no longer uses the fixture adapter but uses the rest adapter. Add store.js to app/assets/javascripts and put the following code in it.

App.Store = DS.Store.extend({
  revision: 12,
  adapter: DS.RESTAdapter.create({
    bulkCommit: false

Serve the javascript from rails

It is advisable to use the latest stable version of ember and ember-data. Download ember-latest.js & ember-data-latest.js from http://builds.emberjs.com/ and put in vendor/assets/javascripts Add the handlebars_assets gem to the Gemfile so that we load handlebars.js and get the assets pipeline to compile our handlebars templates. You may have noticed that we append .hbs to them since this is what the gem looks for rather than .handlebars. We also need to load our ember application javascript files, create a blog.js file

//= require ./store
//= require_tree ./models
//= require_tree ./controllers
//= require_tree ./views
//= require_tree ./helpers
//= require_tree ./templates
//= require ./router
//= require_self

Then add blog, handlebars, ember and ember-data to application.js. Also create our ember app instance inside there.

//= require jquery
//= require jquery_ujs
//= require handlebars
//= require ember-latest
//= require ember-data-latest
//= require_self
//= require blog

window.App = Ember.Application.create({

Start a rails server with rails s and go to localhost:3000 in a browser. You should see the Blog index page with a link to ‘Posts’. Open up the debugger to look at the network traffic. Click on the Posts link and you will see a request to localhost:3000/posts. The response is empty but the application transitions to posts.

Add some data and respond with JSON

We will now add some data for the server to send to the browser. Add some db seeds to db/seeds.rb

post = Post.create( :title => 'First post', :content => 'Text for first post' )
Comment.create(:text => 'Post one comment one', :post_id => post.id)
Comment.create(:text => 'Post one comment two', :post_id => post.id)
post = Post.create( :title => 'Second post', :content => 'Text for second post' )
Comment.create(:text => 'Post two comment one', :post_id => post.id)
Comment.create(:text => 'Post two comment two', :post_id => post.id)
post = Post.create( :title => 'Third post', :content => 'Text for third post' )
Comment.create(:text => 'Post three comment one', :post_id => post.id)
Comment.create(:text => 'Post three comment two', :post_id => post.id)

Use rake db:seed to add the posts and comments. We also need to make sure that our rails application serves JSON in the correct format. We need to add the correct JSON serialiser to the post model to include the comments as comment_ids array. Ember needs the JSON response in the format "posts" : [{...},{...}]

def as_json(options={})
  { :id => self.id, :title => self.title, :content => self.content, :comment_ids =>self.comments.collect{|comment| comment.id} }

We then need to change the posts controller index method to render json using this method

format.json { render :json => { :posts => @posts.as_json } }

as well as in the show method

format.json { render :json => { :post => @post.as_json } }

We also need to change the JSON response in the comments controller show method to

format.json { render :json => { :comment => @comment } }

so that the json is returned as "comment" : {....}

(see http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/)

When fetching the comments ember will request it as /comments?ids[]=1&ids[]=2 ie as an array of ids, change the comments_controller index method to handle that

if params[:ids]
  @comments = []
  params[:ids].each do |id|
   @comments = Comment.all
respond_to do |format|
  format.html # index.html.erb
  format.json { render :json => { :comments => @comments } }

Save new comments to the server

We need to change the CommentsNewController save method so that it sends a POST request to /comments with the new comment in JSON. Change it to:

var post = this.get('controllers.post.content');
var comment = App.Comment.createRecord({ post: post, text: this.get('text') });
comment.get("store").commit(); //this is the new bit, after creating a comment we need to commit it

comment.get("store").commit() tells the comment to commit itself.
Go to /posts/1/comments/new, enter a comment and hit save. You will see some network traffic heading to /comments on the server. Refresh /posts/1 and you will see that it has the new comment. You can use the rails console to convince yourself. Comment.all will have the new one at the end. We can use exactly the same principles to create new posts, why not add it to your app?

Ember JS: MVC in the browser. Part 1 – Routing

Ember JS is a Javascript client side MVC framework featuring all your favourite constructs such as controllers, models, views and routing. Client side means that it all runs inside the browser meaning that rendering times are extremely fast with no calls to the server to fetch pages. Ember has an optional restful data model called ember-data which handles the GET/PUT/POST/DELETE lifecycle of your models. Go to http://emberjs.com and download the starter kit which I used as the skeleton for this application or download the complete code for this part of the tutorial here. Have a look at the video tutorial as well, you will no doubt recognise some overlap with these posts. I primarily wrote this to get everything I had learned about ember in one place, I found the emberjs.com tutorials very useful but also unordered and was constantly flicking between various different sites, stack overflow etc. We will be building a simple blog application using a lot of the facts that can be found in the emberjs.com tutorials but with some pointers and helpers along the way. We will look at the ember components needed to handle the model lifecycle and views and later will write server side code to find, create and save the models. You can use any server framework you like but I prefer to use rails however ASP.net or whatever are just as good as long as they can handle REST and JSON. We will also look at using CORS or JSONP to load data directly to the browser.

For me it was easier to think of an ember app in terms of a rails one so where better to start than with the routes. Our simple application will consist of posts which can have many comments. In Rails (3.x) your routes file would consist of a root and some resources corresponding to the models. So lets say you use some scaffolding to get started

rails new blog
rails generate scaffold Post name:string title:string content:text

This gives us the following in config/routes.rb

resources :posts

We would also normally add a root after deleting public/index.html

root :to => 'welcome#index'

rake routes shows:

posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
root / welcome#index

We want to create a similar route structure in ember.

To begin with we will keep all the html and UI bits in index.html and all the application logic in app.js (look inside the js directory to find it). The ember starter pack has an example index.html, open it in your browser and you will see that it renders a simple page with 3 colours listed. Have a look at it in an editor and you can see the script blocks within the html that define the templates. There is one with an {{outlet}} and an index template. If you look at js/app.js you will see that the IndexRoute returns an array of strings which are rendered into the index template. The templates use handlebars which is similar to erb in rails but is contained within javscript <script> blocks with a type of “text/x-handlebars”. Unfortunately we don’t have the benefit of rails logging what is happening when we go to a url in our application but we can ask ember to tell us what route it is rendering, to do this we will change the main ember application javascript. Open up js/app.js in an editor and change App=Ember.Application.create() to


Log transitions will help us to see what the router is doing when we move from page to page. If you open up a browser console and reload the index page you will see that it says “Transitioned into ‘index'”

We will now add our own bits to the starter app. Start by removing the existing handlebars templates from index.html and add the one shown below. Remember to place it within the html <body> tag.


<script type="text/x-handlebars">
      &copy;2013 Me.


Within this script block we have defined a template which has type text/x-handlebars, this is the basic application template into which other templates will be rendered, as you saw with the index route earlier. Anything wrapped in {{ }} tells handlebars to do something. The {{outlet}} is similar to <%= yield %> in rails, the placeholder where other templates are rendered.
We also need to create our application inside app.js. Remove the section with App.IndexRoute, leaving only the App definition with the LOG_TRANSITIONS we added


We will start by defining a simple router, add the following to app.js

App.Router.map(function() {

and then populate it with a route

App.Router.map(function() {

Refresh the page and you will see that we have transitioned into index but there is nothing there except the header and footer text we specified. That is expected since we removed the index template, we will add them back during part 2. We can use App.Router.router.recognizer.names in the web console to see all the routes. It returns a js object within which all the current routes are show. Use it and you will see that we have the routes index and posts. Seems that it does not behave like you think it would in rails and only creates 2 named routes ‘index’ and ‘posts’ ie ‘/’ and ‘/posts’. What we also need is /posts/:id. To do this we have to create a route for instances of a post.

App.Router.map(function() {
  this.resource('post', { path: '/posts/:post_id' } );

Again this doesn’t quite get us what we want and only gives us the ‘index’, ‘posts’ and ‘post’ routes which will work fine but we want member routes under ‘post’ so that we can show, edit, delete etc. To begin with what we actually want is ‘index’, ‘posts’ and ‘post.index’. ‘post.index’ is ‘/posts/:post_id’ which in ember terms is the equivalent of rails route ‘show’. We want a page which shows all posts and one which shows a single post. We need to add some more to the router for this.

App.Router.map(function() {
  this.resource('post', { path: '/posts/:post_id' }, function() {

We have defined an inner function of the ‘post’ resource where the member routes will be defined. You get ‘post.index’ for free. To look at all the routes you have defined again use App.Router.router.recognizer.names in a browser console. We now have ‘index’, ‘posts’ and ‘post.index’. We have some basic routes defined, now we need some UI magic. In part 2 we will look at templates and handlebars along with the models, store and routes to hook them together.

Ruby on Rails and IIS on Windows 7

Here are the steps I needed to install ruby 1.8, rails 2.3, sqlserver to run our https://github.com/myGrid/methodbox codebase on a Windows 7 platform and run it all under IIS. It should also work for any rails 2 or 3 project.  If you use rmagick or libxml-ruby then pay attention to the installing gems part for some dlls you need to install along with where to get them.

So, having tried various solutions involving fastcgi and url rewrite which I could not get to work on IIS 7.5 under Windows 7 I found http://www.helicontech.com/zoo . I’ve seen the people behind it on various other posts on msdn etc so there is some history of them working on IIS, fastcgi and url rewrite. In fact I think they have had a url rewrite product available for a number of years.

* Install Rails

1) Install the Web Platform Installer from http://www.microsoft.com/web/downloads/platform.aspx
2) Add http://www.helicontech.com/zoo/feed as a new feed
3) From the zoo tab select Blank Ruby on Rails Rails project and Ruby1.8 and click the install button. It will also install other dependencies.
4) When installing the blank project it will pop up and ask you where to put it along with other required details like the name. Make a note of where the project lives since we need a couple of files from it.
5) From the blank rails project we need the web.config files in the projects root and public directories.  Place these in the same place in your rails project directories.  To use Ruby1.9 we need to replace ruby.1.9.pipe in the web.config in the projects root directory with ruby.1.8.pipe. You may also have to add the path to ruby’s bin directory to your environment variables – C:\Ruby18\bin or C:\Ruby19\bin
6) Ensure that the projects directories are writeable by the IIS_IUSRS user.
7) Add the project to IIS with the project path pointing to the rails projects root directory (not public like you would with a rails project under apache).

* Install Git

This is used for version control and can be found on http://git-scm.com/ Install the version marked ‘Full installer for official Git for Windows 1.7.8’ or similar (version name might be different).

* Install required gems (libxml and imagemagick specific instructions)

There are various 3rd party dependencies that the gems that MethodBox requires including imagemagick (ie. rmagick) and libxml-ruby. On windows this requires a little bit of user intervention during the install process. Go to http://www.imagemagick.org/script/binary-releases.php?ImageMagick=uteqfietdab37ghqrvfuvoul55#windows and download http://www.imagemagick.org/download/binaries/ImageMagick-6.7.3-7-Q16-windows-dll.exe
Double click and go through the installer, selecting to install C and C++ header files and libraries from the additional options page
add environment variable CPATH=\path\to\imagemagick\include and LIBRARY_PATH=\path\to\imagemagick\lib

There is a high chance that the libxml-2.2.dll needed for libxml-ruby is not present in the lib folder and will pop up an error.  The dll can be found in C:\Ruby18\lib\ruby\gems\1.8\gems\libxml-ruby-2.2.0-x86-mingw32\lib\libs\  Copy the libxml, iconv and zlib dlls and put in the C:\Ruby18\bin folder.

Note: If you are not using mysql then comment any mysql gem out of the Gemfile. Otherwise the system may complain about libmysql.dll missing.  If you are using mysql you need to copy the dll from the mysql/bin folder to the ruby lib folder.

* SQL server and rails

1) Find out your SQL server details. If your SQL server instance has not been allowed through the firewall then you need to find out its details: open up the sqlserver management console (which you can install along with sqlserver express via the Web Platform Installer – I recommend this way, downloading on its own and installing does not work correctly) and look at your db details.
2) Set up a Data Source Name (DSN) for your ODBC connection.  This is not that well documented so you need to find the C:\Windows\sysWOW64 directory and start the odbcad32 programme.  Then you add a system DSN for your instance of sqlserver.
3) Set up your rails projects database.yml as normal with the following records:

adapter: sqlserver
mode: odbc
dsn: sqlserverapp-dsn (the one you created earlier)
username: user
password: secret
host: localhost (or whatever)

Ruby, Windows and RMagick

Been doing a lot of rails work on windows recently and ran into some issues that needed solved.  Just like on Unix, to get the RMagick gem working on a windows platform you need to install ImageMagick.  Go to http://www.imagemagick.org/script/binary-releases.php?ImageMagick=uteqfietdab37ghqrvfuvoul55#windows and download http://www.imagemagick.org/download/binaries/ImageMagick-6.7.3-7-Q16-windows-dll.exe

Double click and go through the installer, selecting to install C and C++ header files and libraries from the additional options page (this is very important)

Then add environmant variable CPATH=\path\to\imagemagick\include and LIBRARY_PATH=\path\to\imagemagick\lib

You can then ‘gem install rmagick’ and it will build it using the native image magick libraries.

Bundler, OSX and the MysqlCompat::MysqlRes error

If you get the uninitialized constant MysqlCompat::MysqlRes error when trying to run your Rails app all the evidence points to it being a 32 v 64 bit issue.  However, I had built mysql for the x86_64 architecture and the mysql gem installed was also for 64 bits.  So why was I still getting this error.  It turns out that bundler was building the mysql gem in 32 bits.  OSX Snow Leopard ships with Ruby in a universal binary containing the ppc, i386 and x86_64 binaries and for whatever reason bundle install was using the 32 bit ruby and re-building everything even though I had the gems already installed in the system in 64 bit mode.  This could be because the user doing the building was 1) unprivileged and 2) using bundle install \--path=vendor.  Maybe bundler was picking the first version of ruby that was appropriate to the platform.  However, doing bundle install \--deployment also had the same issues. I have no idea why it was rebuilding gems that already existed on my system. The way to get round it was to force bundler to build in 64 bits by using env ARCHFLAGS='-arch x86_64' bundle install --path=vendor
Maybe the best idea is not to use the Ruby that ships with OSX and build one appropriate to your environment in the first place.

Taming the Savage Beast (Forums)

We needed a forum for one of our web projects written in rails and a quick google revealed Savage Beast.  It seemed to fit the bill although needed some css tweeks to co-exist with what we currently have.  However, when clicking on its RSS feed icon it threw an ActionController::Request.relative_url_root method missing error which was fixed by creating the class request_error.rb in initializers with the code below:

class ActionController::Request
def relative_url_root
@@relative_url_root ||= case
when server_software == ‘apache’
@env[“SCRIPT_NAME”].to_s.sub(/\/dispatch\.(fcgi|rb|cgi)$/, ”)


Based on bug reported here: http://railsforum.com/viewtopic.php?pid=73991#p73991.

It all seems to work fine now.