RubyOnRails


Move fast, move early.

And we are moving again. Since we will move now to the official developer blog of my current employer TravelIQ, this site will not be continued. But feel free to join us at our shiny new place around trafikant.de.

And of cource all articles published here are available as well at our new home.

For the communication between client and server in an AJAX environment JSON became a very important part. It is easy to use, to understand and supported from the most important programming languages (if not native like in Javascript, at least there is a framefork provided). Usually one would use the default encoders to translate the objects provided on the one side to data represented using JSON and then again decode to extract the objects.

But in some cases using the usual encoders would not be enough. For these cases Rails provides a very easy framework to plug you own encoders for you own class. The process to achieve that is simple and again easy to understand, but the procedure can leave some obstacles on the road that need to be survived.

The following sample will explain, what can happen and will show a solution to avoid the most problematic JSON CircularReferenceError.

class MyArray < Array
  attr_accessor :providers
end

The above noted class provides a new type of Arrays containing a new attribute to better identify the providers of the array. Using this array in Ruby is now problem, since the runtime will always identify this object correctly. But what about serialization? Here the problem starts. The serialization will not uses the attribute and simply ignore it. So the next step would be to write an own encoder to provied a specific JSON encoding.

module ActiveSupport
  module JSON
    module Encoders
      define_encoder MyArray do | fra |
        myfra = fra.compact
        returning( result = '{' ) do
          i = -1
          result << '"providers": ' << myfra.providers.to_json << ', '
          result << '"length": ' << "#{myfra.size}" << ', '
     
            result << myfra.map do | val |
              [ i += 1, val ].map { |value| value.to_json } * ': '
            end * ', '

          result << '}'
        end

This code provides a simple Encoder for our MyArray class and adds the provider to our data string. Of course on the client side (or the other side), this will not result in an array but more an object that has integers as attributes and the values as values for these attributes. But in Javascript this would feel like an array.

// ...
// data is the variable containing the parsed object fromm our ruby side.
for (var i=0; i < data.length; i++){
  alert(data[i]);
}

for (i=0; i < data.providers.length; i++){
  alert(data.providers[i]);
}

Well, and this is what we wanted to achieve. An user defined array class containing additional attributes to carry additional data. So far, so good. But it is not as simple as it seems. Just imagine the following example that creates an empty instance of MyArray containing an emtpty providers Array. In the beginning everything is fine, but as soon as you want to serialize the instance using our user defined JSON Encoder, we will receive a circular reference error. Before I will explain a solution for our problem let’s have a look on what happens while serializeing. At first for each object a new stack is created, this stack contains all objects that are to be serialized. The reason for this stack is simple: If the object contains an instance of itself, this would result in a circular reference and an endless loop.

But why do we get an circular reference error? We put at first an instance of our MyArray class, and then an instance of an normal Array into the stack list. It looks like there is no circular reference! But there is, or at least for Ruby it looks like there is! To explain, have a look at the following piece of code:

a = MyArray.new
b = Array.new # Or simply []
puts a == b

Actually a == b is what the include? call is doing when recursing the object stack. The result of this piece of code is true. The instance of MyArray has the same == method as Array, they share it. Since Array overwrite the default == method of Object, the result is true. And this is the simple and short reason why we receive a CircularReferenceError message.

To avoid receiving this error, the first and most simple reason would be to define an own == method for MyArray and actually this is the most safe method. Another idea would be to extend the include? method used by the JSON Encoder. Instead of simply calling == for all objects, we could combine this with an instance check.

  # This method is directly taken from Rails json.rb
  def raise_on_circular_reference(value)
          stack = Thread.current[REFERENCE_STACK_VARIABLE] ||= []
          raise CircularReferenceError, 'object references itself' if
            stack.include? value && stack.find {|e| e.instance_of? value.class}
          stack << value
          yield
        ensure
          stack.pop
  end

The include condition is now extended using the stack.find {|e| e.instance_of? value.class} fragment. The circular reference error will only be raised if the referenced stack element is an instance of the current value class.

The second possibility may have side effects of that I am not sure. But I think I will investigate in that direction. If you have any ideas, please tell me!

Everybody, who has ever tried, knows how difficult it is to design fluid layouts. Designers and others don’t make it easier. But todays computers do not allow to ignore the screen size and deliver just one fixed layout. The minimum would be to build two or three static sizes:

  1. one for mobile devices: something about 300px in width, but this is just a guess. iPhone might improve this issue.
  2. one for regular screens – 1024 x 768. Works on small (widescreen) notebooks and most other elderly monitors
  3. one for the large ones, that never heard of leaving the full screen. We decided to go for 1280 x 1024

This leads to the problem, that graphics have to scale to certain sizes, margins and paddings should grow and the font-size has to be reviewed. One could argue, that just a redefinion of the font size within the body should be sufficent. But nobody wants to enlarge every tiny bit.

So you have to deliver different stylesheets for every supported size. While there are several possibilties, they all have certain drawbacks.

  1. Separate the different css files completely: While writing the styles, this comes handy, you have all definitions that influence the view at hand. No side effects,you didn’t recognize. But when maintaining the code, adding new UI elements, this becomes dirty. You will inevitably loose changes in the one or the other way and you have to synchronize the styles manually.
  2. Have a default style sheet and redefine the changes in another one: This solves the synchronizing issue, mainly. But the definition of the derived style gets pretty difficult. There is no way to recognize unintended side effects, when editing the default style.
  3. Have a basic style sheet and define the size-related statements in other files: What should that be good for, except bandwidth concerns.
  4. and finally: Define everything in place, use one stylesheet to rule them all. Introduce variables to compute the needed sizes or add control structures to get the correct results.

But wait – there is no such thing like variables or control structures in Cascading Stylesheets. But they are there in Ruby and in Erb, so why shouldn’t we combine them, as we do in HTML?

Rails makes everything handy from now on. Others ( Dirt simple .rcss templates, Dynamic CSS in Ruby on Rails) have already described, how to add rcss to your Rails environment. There is even a Gem at Rubyforge, which may be included easily. We have made our own contribution, specific to our needs.

Building rcss templates in Rails

Add the following to your config/routes.rb

map.connect 'rcss/:rcss', :controller => 'rcss', :action => 'dispatch'

In Rails 1.2.1 which has been released recently, the configuration of Routes as been changed significantly. It is said to be more powerful and faster. For our configuration we need only small changes. Add the following line if you are using the lastest Rails:

map.connect 'rcss/:rcss.:format', :controller => 'rcss', :action => 'dispatch'

Generate a controller to handle your generated stylesheets.

script/generate controller rcss

And fill it with contents.

class RcssController < ApplicationController
  layout nil
  session :off

  def dispatch
    if rcss = params[:rcss] and
       action_name = rcss.gsub(/\.r?css$/i, '').to_sym and
       respond_to?( action_name )
        file_path = send( action_name )
        render :file => file_path, :content_type => "text/css"
    else
      render(:nothing => true, :status => 404)
    end
  end

For every style sheet you would like to use with your HTML add a method named after it. So style.css or style.rcss if you like would become

  def style
    @custom_variable = true # May be used within the style sheet
    "#{RAILS_ROOT}/app/views/rcss/style.rcss"
  end

with the corresponding rcss template

<% if @custom_variable %>
   body * { background-color: green; } 
<% else %>
   body * { background-color: yellow; } 
<% end %>

Now you are able to keep all the definitions in one place. You may recognize all dependencies and react correctly.

Further topics:

  1. What does that mean for caching?
  2. How do we activate the different styles on the client side to adopt to different screen resolutions?