Another Concise Code Example

April 26, 2008 4:54pm | 5 Comments | , , and

This is just another example showing how I refactor code down to its bare minimum. The reason why I do this so much (and indeed I think why ruby is so easy to read compared to other languages) is because it makes my code more readable and less of a bugger to pick up after a while.

class Page
    attr_accessor :parent_id

    def old_parent
    # The returns aren't needed here in ruby, but in other
    # languages using this logic block you would require
    # the returns, so I left them in here.

    if self.parent?
      return Page.find( self.parent_id )
    else
      return false
    end
  end

  def parent
    return Page.find( self.parent_id ) if self.parent?
    false
  end

end

old_parent and parent return exactly the same, but one is 2 lines compared to 5 and easier to read.

Update: Ciaran pointed out that the Page.parent method would only ever return false. Added the return statement to it to fix the bug.

Command line tricks: Scripting Languages

February 14, 2008 4:24pm | 3 Comments | , , , , , and

To search your php.ini file quickly and easily with the option to use regular expressions, I tend to drop back to the cli. The reason for this is I can easily parse the output of phpinfo() with grep, and can do various things with the output, could even pass it to a script if I really wanted to.

Here is the line I use to search phpinfo()

echo "<?php phpinfo() ?>" | php | grep -i $search_string

It passes the string through the php interpreter and then searches through it with grep....

More...

Refactoring code logically

February 12, 2008 12:28pm | 2 Comments | , , , , , and

And now an example of how I write my ruby code and get it down to the bare, readable, minimum code needed. This is real life code taken from a website I'm building, but I've changed the objects to a blog post because more people will relate to that easier.

The show object has an id passed in using the params Hash, I want to check if that post exists in the database first. If it does, then render the page, and if it doesn't return a 404 error page.

So I start off by writing this in longhand ruby, I'm using the merb framework with DataMapper ORM by the way....

More...

Use datamapper sessions with merb & datamapper

February 5, 2008 8:27pm | 1 Comment | , , , , , , , and

Issue

Can't use merb sessions with datamapper & mysql, get back an error about needing an id on the text column or something (I had the error a couple of days ago.)

Solution

I suggest grabbing merb_datamapper svn source to fix this in. To do so make sure you have subversion installed on your machine (I'm assuming a Unix based machine here.)

  1. Checkout the source ...

More...