A ruby idea

In ruby you can check ranges via de ‘range’ language construct. For example: (12..23).include?( value).
But how about chaining ‘<', '<=', '=>‘ and ‘>’ operators.

For example. currently in Ruby I must write the following

if 10 < x && x < 15
  # code
end

Why isn’t it possible to write

if 10 < x < 15
  # code
end

Well in fact it is possible with some hacks :)
The example below is only valid for Fixnum, but it describes the possibilities:

The hack is to just simply return the right hand. In Ruby this shouldn’t be a problem, because every object/values is true except false and nil.

class Fixnum
  def <(val)
    super ? val : false
  end
  def <=(val)
    super ? val : false
  end
  def >(val)
    super ? val : false
  end
  def >=(val)
    super ? val : false
  end
end

To make this work the FalseClass should also support these operators, and simply return false to make the complete expression return false if one of them fails:


class FalseClass
  def <(val)
    false
  end
  alias :<= :<
  alias :> :<
  alias :>= :<
end

So 10 < x just returns 'x' on succes and returns false on error.

if 10 < x < 15
  # code
end

I'm wondering what could/would be the 'problem' by using this construct? Is there a specific reason this has not been implemented this way?

BTW: just found a 'nice' implementation for this construct on: http://refactormycode.com/codes/1284-chained-comparisons-in-ruby

[:<, :>, :<=, :>=].each do |operator|
  [Float, Fixnum, Comparable].each do |klass|
    klass.class_eval {
      alias_method("__#{operator}__", operator)
      define_method(operator) do |operand|
        send("__#{operator}__", operand) and operand
      end
    }
  end
  FalseClass.send(:define_method, operator) { false }
end

My ruby external-encoding hack

Reading (text)-files from disk is very easy in Ruby.

content = IO.read( "filename.txt" )

When you are trying to do something with this content you can get in trouble.

content.split(",")  # => invalid byte sequence in UTF-8

I’ve setup my environment very nicely, so Ruby treats external files as UTF-8. The trouble begins when you are trying to handle files that are encoded in the ISO-8859-1 or CP-1252 format and Ruby thinks they are UTF-8.

To accept both UTF-8 and ISO-8858-? formats I’ve implemented the following hack:

  def convert_to_utf8(content)
    if content.valid_encoding?
      content
    else
      content.force_encoding("ISO-8859-1").encode("UTF-8")
    end
  end

  # reading the content:
  content = convert_to_utf8 IO.read( "filename.txt" ) 

This hack works for me because the text-files I use are in one of those formats.

has_many tricky replace method

Today I discovered a small bug / feature of rails 3.1.3.

Having the following structure:

class Item < ActiveRecord::Base
  has_many :tags
end

class Tag < ActiveRecord::Base
  # Tag has a boolean flag 'enabled'
  belongs_to :item
end

It’s possible to completely replace the has_many collection
with a new collection. Make this collection:

item = Item.find(1)
tags = [
  item.tags.create( :enabled => true, :name => "tag1" )
]

All fine for the moment. As expected the enabled flag of the first item is set:

tags[0].name      # => "tag1"
tags[0].enabled?  # => true

Now replacing the existing tags:

item.tags.replace( tags )
item.tags[0].name        # => "tag1"
item.tags[0].enabled?    # => false

What?? It just forgot the enabled flag!!

The way to replace the items is by assigning:

item.tags = tags
item.tags[0].name        # => "tag1"
item.tags[0].enabled?    # => true

So remember when replacing collections of has_many do not replace them but assign them….

Slow response testing localhost sites in Google Chrome on Mac OS X

Last week I noticed the response of localhost requests were slow in Google Chrome, but responded very quickly in Safari. I suspected Chrome was submitting my local requests to it’s data hunger servers to build an even better profile of me.
I tweaked a lot of Chrome settings so everything would be kept private, but no success. After several attempts I found the problem:

To test multiple sites and testing multi-domain rails applications I’ve changed my /etc/hosts file to contain the following items.

127.0.0.1 nice-domain.local
127.0.0.1 nice.sub-domain.local
127.0.0.1 gamecreatures.local

So calling: “gamecreatures.local” in Chrome causes a too long delay for showing something..
calling “gamecreatures.local” in Safari responded instantly..

After doing some research, I’ve learned Apple is doing something special with the .local postfix. It is used by the Bonjour services somehow. I don’t know exactly what, but they do…

So changing all the extension from “.local” to something else for example “.loc” solved the issue for me:

127.0.0.1 nice-domain.loc
127.0.0.1 nice.sub-domain.loc
127.0.0.1 gamecreatures.loc

Now Chrome also responds instantly…
Sorry Google for “assuming” you trying to steal all data from me… (Or should I use the _nomap extension for this one too ?!?)

Rails 3.1 Assets Precompilation

Today I tried to ‘release’ our rails 3.1 product to the production environment. Which of course has precompiled assets.

The app deployed nicely. But when I tried to start the app, I’ve got the following error:

ActionView::Template::Error (locales/nl.js isn't precompiled):
...

Deploying the app with capistrano (which precompiles my assets) did not compile my javascript-locales.

The cause of this seeems to the that the assets pipeline precompilation task, only precompiles the application.js file…

To add extra files for precompilation, place the following code in your config/application.rb:

    config.assets.precompile << "locales/*.js"
    config.assets.precompile += %w(rails_admin/rails_admin.js rails_admin/rails_admin.css)

This examples precompiles ALL my locale files in the app/assets/locales/* directory.

And as a bonus it also compiles the assets of the the rails_admin plugin.