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
  end

the following routes should now be usable,

/books/1/chapters

and

/chapters/6
/chapters/6/edit
/chapters/6/delete

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.

The end of black hat SEO copywriting?

SEO is something of a dirty word, particularly for many legitimate web developers. It’s no wonder, with so many ‘black hatters’ out there clogging up the internet with their rubbish content.

Thankfully, Google is well aware of black hat and is constantly revising its algorithm in order to prevent this sort of trickery. In this post, Martin Harrison of copywriting agency Copify takes a look at some of the common black hat tricks employed by SEO copywriters and the reasons why they no longer work.

Keyword stuffing

Time was, the only thing you needed to do in order to rank on Google was stuff your targeted keyword in there a dozen or so times and bingo, first page ranking. This resulted in a lot of poorly written, spammy copy like this:

“Do you like spammy SEO copy? Well you’ve come to the right place, because here at spammySEOcopy.com we are spammy SEO copy experts. This is a one stop shop for all of your spammy SEO copy needs.”

Thankfully, this is no longer considered SEO best practice as Google has become much more advanced in the way that it indexes content, looking at aspects such as semantic relevance and domain authority to establish whether or not a page is relevant to a query.

Excessive linking

Exact match anchor links are still a big factor in SEO, but some people take it to the extreme, linking every second word on their site. This technique may have worked once, but nowadays Google is wise to it, and the more links you put on a page the less valuable they become.

Hidden text

White text on a white background used to be a common black hat trick to get a page to rank, without offending anybody with rubbish copy. Now, it’s likely to lead to your page, if not your whole site being taken out of Google’s index.

Write for humans first, spiders second

If you want to create a great website, it’s important to remember the golden rule, write for humans first and foremost. That way, you will have copy that sells your products and services effectively and provides real value for visitors. As a result, you are much more likely to create something that people will naturally want to share and return to, which is far more valuable than any black hat SEO.

Posted in SEO

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.

http://stackoverflow.com/questions/6094766/windows-phone-7-webbrowser-content-height

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.

onLoad="window.external.notify(''+document.getElementById('content').offsetHeight);"

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

#!/bin/bash
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"
 end
end

f = Freeza.new
f.hello

class Freeza # twice
  def goodbye
    puts "goodbye"
  end
end

f.goodbye

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

Freeze it

Freeza.freeze

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.

begin

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

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

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"
  end
end

f = Defrosted.new

f.hellohello

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"
  end
end

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

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
  end
 
  def getBinding
    return binding()
  end
end

e = Editor.new
e.say("hello world")

# now for a bit of monkey typing
monkey = <<MONKEY
  def reverseSaying(saying)
    self.say(saying.reverse)
  end

  self.reverseSaying("hello world")
MONKEY


puts monkey

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

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

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)
    self.say(saying.reverse)
  end

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]

line_num=0

tokenizer = Syntax.load "ruby"

file = File.new(filename,"r")
while (line = file.gets)

c_line = ""

tokenizer.tokenize( line ) do |token|
case token.group.to_s
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: #{token.group}"
end
end

line_num = line_num + 1

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

end

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;
            }
            else
            {
                $this->children[$comment['parent_id']][] = $comment;
            }
        }
        $this->print_comments();
    }

    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";

        $this->tabulate($depth+1);

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

    /**
     * @param array $comment
     * @param int $depth
     */
    private function print_parent($comment, $depth = 0)
    {
        $this->tabulate($depth);
        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);
            }
        }
        $this->tabulate($depth);
        echo "</ul>n";
    }

    private function print_comments()
    {
        foreach ($this->parents as $c)
        {
            $this->print_parent($c);
        }
    }

}

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

$this->load->library('threaded');

and name it threaded.php

This library is based on the following post, http://www.jongales.com/blog/2009/01/27/php-class-for-threaded-comments/

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->threaded->arrange($comments);

This is the result you should get in html

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