Am I mapping my routes correctly

I am trying to implement shallow routes (being able to list the index of a model through the parent model but without have to access child records through the parent on other actions than index)

  resources :books, do
    resources :chapters, :shallow => true

the following routes should now be usable,




but I get a routing error

No route matches {:controller=>”chapters”}

What am I doing wrong?

I can code it to do /books/1/chapters/6/edit for example but I would rather it use shallow routes.

How do you resize a webbrowser control to fit on a html element?

I thought I had found the solution to this problem in the following question, but it does not behave as planned.

So I am pretty much struggling with this, but I guess if the answers can go in here it will be as useful on here than it is on stack overflow

I am loading some html content into a div that is inside of a webbrowser control, when the page has loaded I pass the height of the div back to the control with this.


and in the ScriptNotify call back i’m currently doing to something like this

private void PlayerBrowser_ScriptNotify(object sender, NotifyEventArgs e)
   PlayerBrowser.Height = Convert.ToDouble(e.Value) * 0.5;

some values return but when the content is snug at the top of the webbrowser control i will truncate some of the content from the bottom.

and when i adjust the height (by changing 0.5 to another number) so that there should be more than enough space to fit the content in, it will centre it all vertically and then still truncate the bottom of the control.

my html is being specified like this.

string newHtmlString = "<head><meta charset='Windows-1257'><meta name='viewport' content='width=device-width' />" +
  "<meta name='viewport' content='user-scalable=no' /><meta name='viewport' content='initial-scale = 1.0' />" +
  "<meta name='HandheldFriendly' content='true' /><meta name='target-densitydpi=device-dpi' /></head>";

newHtmlString += "<body        onLoad="window.external.notify(''+document.getElementById('content').offsetHeight);" ><div id='content'>";            
newHtmlString += htmlContent + "</div></body>";

this code is closest i’ve found up to now for the solution to my problem, so It would be nice for someone to let me know where I have gone wrong.

Posted in Uncategorized

The reason speed cameras are out of date

The whole concept of varying speeds on roads is out of date.

What makes driving safe is the distance from the car in front.

If the governments were to create ‘safe distance’ cameras rather than speed cameras, it would be able to enforce a safe time between cars of 3-4 seconds, that way cars have enough time to stop at any speeds allowing for reaction times.

This distance enforcement would also help greatly in rush hour traffic as keeping a distance between 3 and 4 seconds would keep the cars flowing evenly.

Posted in Uncategorized

RVM aliasing and actually scratch that.

I’ve just started use rvm in order to switch ruby and rails versions, mainly it’s to switch to rails3 and still have rails 2 as my main rails installation.

This way I can have rails2 for prebuilt applications such as fatfreecrm and the like that are still on rails 2.

It is also possible to install rails3 to start off with and to switch to version 2.3.8 but I started off with 2.3.8 so that how my setup is.

One thing I found very tiredsome was typing

rvm use ruby-1.8.7-p249

followed by

rvm gemset use rails3

so a bit of googling for “rvm alias” comes up with this:

rvm alias create ruby-1.8 ruby-1.8.7-p249

then you just have to type

rvm use ruby-1.8.7;rvm gemset use rails3

I still don’t like typing stuff

Instead i’ve decided to use a bash script in my project files

rvm use ruby-1.8.7-p249
rvm gemset use rails3

which will switch for me when I run it.

If there’s a way to run a script automatically without watching a folder using a particular os I would be interested in knowing.

There’s also a gem called rvmify which will separate gemfiles for you even for the same version of rails (maybe this app works with one version of a gem but breaks in a newer one)

*If you are wondering how to create a gemset, make sure you are using a non-system ruby installation. so `rvm install ruby-1.8.7-p249` for a mac. and then `rvm use ruby-1.8.7-p249` followed by `gem install ruby -v 3`

*turns out rvm is even more awesome with an .rvmrc it’ll do the folder monitoring and switch versions of ruby/rails when you enter that folder.

Something like:

rvm use 1.8.7@rails3 –create

Is the proper way to do it, thanks to ['john','toby','ryan bates','underpants gnome']

I hope nobody minds my blurting out what I learn and then being corrected.

Posted in Uncategorized

Freezing classes and the nearest thing to “unfreezing”

Freezing is a way to stop classes from being changed in ruby, it’s a way to be a bit of a tyrant with your code.

A preferable way to manage other contributors is to use git and merge changes that other coders have committed, and if the code is below par, just ask the nicely for the functionality to be extended via modules for example or just reject those changes.

Here’s how you add method to a class using monkey patching.

class Freeza # you can define a class once
 def hello
   puts "hello"

f =

class Freeza # twice
  def goodbye
    puts "goodbye"


I have now decided that I don’t want anything added to this class.

Freeze it


Now I have changed my mind, or another coder wants to add functionality.
Notice how I have wrapped the code in a begin and rescue error catch.


  class Freeza
    def hello
      puts "is it me you're looking for"

rescue RuntimeError # this is what we'll get instead
  puts "Get back to where you once belonged"

Now that didn’t work

There is no way to unfreeze the class so we need to find a way to unfreeze somehow.

You can inherit from a frozen class and that will not be frozen.

So let’s try that.

class Defrosted < Freeza
  def hellohello
    puts "hello hello"

f =


Thats all good, but you might want to convert a variable based on the first class and keep the the values from the old class so this is not very flexible, as you are just replacing a variable.

Freezing isn’t nice

Just don’t freeze, but also keep monkey patching to minimum as it’s one of the most powerful tools in ruby. But it can leave a mess of methods spread across multiple files without form.

Once certain monkey patches become popular then change them to the better way of doing it which is using modules.

You can use modules if you plan to have a variable which has the base functionality of a class, yet with a bit more functionality added.

Here’s how this is done.

module MoCowBell
  def donk
    puts "donk"

# i want the variable f to make cowbell noises
f.extend MoCowBell

Now that overcomes the potential freezes of objects by extending the functionality.

But I cannot find a legitimate use for freezing, but also modules are nicer than monkey patches.

Posted in Uncategorized

Syntax highlighting and more in ruby

In a previous post I used the ‘syntax’ gem to process text into tags which could then be tagged with terminal colour codes.

There’s a plugin which already does all of this called coderay, I will combine this with highline (to control the input and output and maybe create an interface too)

require "rubygems"
require "highline/import"
require "coderay"

class Editor
  def say(saying)
    puts saying
  def getBinding
    return binding()

e =
e.say("hello world")

# now for a bit of monkey typing
monkey = <<MONKEY
  def reverseSaying(saying)

  self.reverseSaying("hello world")

puts monkey

eval("reverseSaying('hello world')",e.getBinding)

# now try to monkey patch user input
usermonkeysay = ask("Monkey do?")
puts CodeRay.scan(usermonkeysay,:ruby).term

One thing you might have noticed is that I have a function called getBinding in the ‘Editor’ class, what this does is return a handle to the current class to modify that class programmatically.

When we have the binding, we can do evil things on that class. I mean ‘eval’, but rather than a straight up eval you can do an eval within the context of that class.

And in ruby you can eval this inside of the context of the class

  def reverseSaying(saying)

Something like a ‘def’ in the context of the binding will let you run that function later on using the binding.

What does this mean?

A text editor which took advantage of this (something like diakonos, redcar maybe) would be able to provide user friendly commands such as open, save, gotoLine, regex, replace, column(x,y, w, h), select(x,y,w,h), copy, paste.

This would provide a clear level of abstraction between a command mode and text entry in editors.

My plan is to have a 3 pane editor with a readonly text view, a text entry box and a command box.

Posted in Uncategorized

A command line syntax highlighter written in Ruby

Here is the syntax highlighting cat, which I shall call cax.

#!/usr/bin/env ruby
require 'syntax/convertors/html'
require 'rainbow'

filename = ARGV[0]
puts ARGV[0]


tokenizer = Syntax.load "ruby"

file =,"r")
while (line = file.gets)

c_line = ""

tokenizer.tokenize( line ) do |token|
when "string" then c_line = c_line + token.color(:green)
when "ident" then c_line = c_line + token.color(:magenta)
when "normal" then c_line = c_line + token.color(:cyan)
when "keyword" then c_line = c_line + token.color(:red)
when "punct" then c_line = c_line + token.color(:white)
when "symbol" then c_line = c_line + token.color(:white)
when "number" then c_line = c_line + token.color(:white)
when "expr" then c_line = c_line + token.color(:white)
when "comment" then c_line = c_line + token.color(:yellow)
when "constant" then c_line = c_line + token.color(85,85,85) # only named colors show on win32
else c_line = c_line + "  group: #{}"

line_num = line_num + 1

print (line_num.to_s.rjust(4) + ":").color(:white) + c_line


And this is what the output looks like:

It’s obviously missing the theming of the coloured output which I could add in another version.

It requires the rainbow and syntax gems to get working. and on windows you’ll need the win32console gem to see the colours.

Posted in Uncategorized

Threaded array library for Codeigniter

This library take an array of comments (can also be anything with ids and parent_ids)

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class threaded

    public $parents  = array();
    public $children = array();

     * @param array $comments
    public function arrange($comments)
        foreach ($comments as $comment)
            if ($comment['parent_id'] === NULL)
                $this->parents[$comment['id']][] = $comment;
                $this->children[$comment['parent_id']][] = $comment;

    private function tabulate($depth)
        for ($depth; $depth > 0; $depth--)
            echo "t";

     * @param array $comment
     * @param int $depth
    private function format_comment($comment, $depth)

        echo "n";


        echo "<li>";
        echo $comment['text'];
        echo "</li>n";

     * @param array $comment
     * @param int $depth
    private function print_parent($comment, $depth = 0)
        echo "<ul>";
        foreach ($comment as $c)
            $this->format_comment($c, $depth);

            if (isset($this->children[$c['id']]))
                $this->print_parent($this->children[$c['id']], $depth + 1);
        echo "</ul>n";

    private function print_comments()
        foreach ($this->parents as $c)


To use the library, put it in “libraries” and load in codeigniter with


and name it threaded.php

This library is based on the following post,

So the array we would use is the same as the above blog post,

$comments = array(  array('id'=>1, 'parent_id'=>NULL,   'text'=>'Parent'),
                   array('id'=>2, 'parent_id'=>1,      'text'=>'Child'),
                   array('id'=>3, 'parent_id'=>2,      'text'=>'Child Third level'),
                   array('id'=>4, 'parent_id'=>NULL,   'text'=>'Second Parent'),
                   array('id'=>5, 'parent_id'=>4,   'text'=>'Second Child')

and you process the array into unordered lists like this.


This is the result you should get in html

            <li>Child Third level</li>
    <li>Second Parent</li>
        <li>Second Child</li>
Posted in Uncategorized


Codeigniter is great!! But sometimes codeugbuter is a good enough search in google!!

Google must be doing a nearest key search in it’s search algorithm!

Posted in Uncategorized