Install Passenger (mod_rails) in Snow Leopard 64 bit

Update: passenger 2.2.5 release notes states that there are know issues with Snow Leopard, but developers didn’t had chance to test them out yet. I personally found no problems on 2.2.4. To upgrade simply run:

sudo gem install passenger
sudo passenger-install-apache2-module

and change apache config according to new version. Follow me on twitter for up to date info.


The installation works out as usual and it’s pretty straightforward, version 2.2.4 2.2.5 and using stock Apache which comes with Snow Leopard as default.

Install Xcode from Snow Leopard DVD, and it would be also wise to upgrade rubygems before doing this operation, search older posts.

Install the gem:

sudo gem install passenger
sudo passenger-install-apache2-module
sudo mate /etc/apache2/other/passenger.conf

passenger.conf doesn’t exists on a vanilla installation (of course), therefore create it or look below. I’m also using the “mate” command, which fires up TextMate, replace “mate ” with your preferred text editor, like vi, nano, etc.

If you want to use your personal configuration file instead of passenger.conf:

sudo mate /etc/apache2/users/username.conf

Replace username with your username in Snow Leopard.

Paste those lines in:

LoadModule passenger_module /Library/Ruby/Gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
PassengerRoot /Library/Ruby/Gems/1.8/gems/passenger-2.2.5
PassengerRuby /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
 
RailsEnv development # or production, but anyway production it's the default value if you don't specify.

Now edit the main file:

sudo mate /etc/apache2/httpd.conf

Around line 465 you will find the commented line:

465
#Include /private/etc/apache2/extra/httpd-vhosts.conf

Remove the # and save the file, this will make Apache pickup extra vhost configuration file.

Open up your Control Panel, go into Shares (Condivisione in Italian), Web share, toggle the checkbox and leave it enabled to reboot Apache and let it pickup those changes.

I’m refraining from installing the complementary PassengerPane at this time since it still uses RubyCocoa instead of MacRuby and its last update is dated 2008, therefore open up:

sudo mate /etc/apache2/extra/httpd-vhosts.conf

and paste a similar code to deploy your rails application:

<Virtualhost *:80>
   ServerName www.yourhost.com
   DocumentRoot /somewhere/public    # < -- be sure to point to 'public'!
</VirtualHost>

Reboot again Apache as described above, as an extra as usual you can edit /etc/hosts to add your ServerName mapped to 0.0.0.0 or 127.0.0.1 or what you prefer by writing a simple line:

127.0.0.1 www.yourhost.com

There’s another method of adding custom hostnames by not tampering with /etc/hosts, but I’ll leave it for another blog post.

$1.99 domains with SSL purchase!

Glimmerblocker: block ads in Safari 64 bit mode on Snow Leopard

GlimmerBlocker
Safari AdBlock worked quite well, however since Input Managers are finally totally discontinued in Snow Leopard we can’t use it in Safari running 64 bit mode.

In fact, as the developer states, a new version of Safari Adblock is out in the wild but requires you to run Safari in 32 bit mode, by checking the appropriate flag in Get Info window of Safari.

But since I’m running a 64 bit operating system, kernel and application, I took a step further and began hunting for the appropriate tool and seems that I found it.

GlimmerBlocker doesn’t hack Safari, instead it runs a local proxy to filter ads, pretty neat if you ask me.

And for this reason after the installation you won’t find preferences directly in Safari, instead you’ll find them in your Control Panel, directly in 64 bit mode (PrefPanels that are still 32 bit requires you to reopen the whole Control Panel in 32 bit mode).

The only thing is that when blocking an ads, Adblock removed visually the ads, without leaving empty spaces, meanwhile GlimmerBlocker does (depends on the site you are visiting); however this doesn’t change the fact that it’s an excellent replacement.

There are also other solid features, ranging from creating your own lists, hacking with javascript to let a page behave like you want and showing youtube download links. By running a customizable proxy transparently like this possibilities are infinite, like using it with other browsers and other native applications which uses http. You can even setup your iPod or iPhone to filter ads when over WiFi.

Thumbs up for this software.

Ruby ordered hash tip with Rails

This is quite old, as many of you ruby coders knows that ruby 1.8 doesn’t keep a Hash ordered, while 1.9 does.

This is seldom necessary however, there are bit of codes where it’s important to have the Hash keep the order:

# ruby 1.8.7
>> {:a => "a", :c => "c", :b => "b"}
=> {:b => "b", :c => "c", :a => "a"}
# ruby 1.9.1
>> {:a => "a", :c => "c", :b => "b"}
=> {:a => "a", :c => "c", :b => "b"}

If then you’re using Rails and Ruby 1.8, instead of relying on some kind of black magic sorting by keys or values you can access directly the namespaced ActiveSupport::OrderedHash like this:

1
2
3
4
5
  def build_recurring_hash
    returning(ActiveSupport::OrderedHash.new) do |map|
      (1..5).each{ |n| map[n] = n }
    end
  end

Install Git from source on Snow Leopard 64 bit

There are many methods to get git running on Snow Leopard, this is the source approach.

Go to http://git-scm.com/ and download the latest package (1.6.4.3 as of writing).

Decompress it in a directory, and run this command:

make prefix=/usr/local all
kain-osx:git-1.6.4.3 kain$ lipo -detailed_info git
input file git is not a fat file
Non-fat file: git is architecture: x86_64

seems good, issue:

sudo make prefix=/usr/local install

to install.

test:

kain-osx:~ kain$ git --version
git version 1.6.4.3
kain-osx:~ kain$ which git
/usr/local/bin/git

Of course be sure that /usr/local/bin is in your $PATH.

My Rails .gitignore

config/database.yml
config/*.sphinx.conf
config/s3_credentials.yml
*~
*.cache
*.log
*.pid
tmp/**/*
.DS_Store
db/cstore/**
db/sphinx/**
doc/api
doc/app
doc/plugins
doc/*.dot
coverage/*
db/*.sqlite3
*.tmproj
*.sw?

To always ignore those files system-wide:

git config --global core.excludesfile /path/to/.gitignore

How to install pg (postgresql) gem on Snow Leopard, 64 bit

Install PostgreSQL from source/port for this, does not currently build against binary package.
PATH should be /usr/local/pgsql.

export PATH=/usr/local/pgsql/bin:${PATH}
env ARCHFLAGS="-arch x86_64" gem install pg

Or if you are using macports:

export PATH=/opt/local/lib/postgresql83/bin:${PATH}
env ARCHFLAGS="-arch x86_64" gem install pg

How to mirror a SVN repository on GitHub

Start by creating a project on github.
In this example we will mirror Sphinx search engine.

On your server or local machine create a new git repository, with the same name of the github repo.

mkdir ~/src
mkdir ~/src/sphinx
cd ~/src/sphinx
git init

Now setup the SVN repository as a remote source to track.
It should be noted that the ‘-T’ switch points git directly to the trunk, which is fine for our purposes.

git svn init -T http://sphinxsearch.googlecode.com/svn/trunk

Perform the initial pull.

git svn fetch

This will take some time, based on the size of the remote repository.

After the first pull is finished, go ahead and run the garbage collector, this will help to speed up things and reduce size.

git gc

I’m going to use a different public key for pushing to github, with no passphrase.

ssh-keygen -t dsa -f ~/.ssh/id_dsa_github_for_mirroring

Now, edit ‘.ssh/config’ and add

Host githubmirror
User git
Hostname github.com
IdentityFile /home/yourusername/.ssh/id_dsa_github_for_mirroring

Now, copy and paste your public key into your github account.

cat ~/.ssh/id_dsa_github_for_mirroring.pub

Add the origin, do the first push.

git remote add origin git@githubmirror:yourgitusername/sphinx.git
git push origin master

To keep stuff in sync we need to do

git svn rebase
git push origin master

This is an operation you should do every X minutes or so.
Better setup a cronjob to handle that.

mkdir scripts
cd scripts
nano mirror.sh

and add the following:

#!/bin/sh
cd /home/yourusername/src/$1
git svn rebase
git push origin master

Save and close the file.

Now edit a crontab entry:

crontab -e

Press ‘i’ and start pasting this line:

*/15 * * * * /home/yourusername/scripts/mirror.sh sphinx >/dev/null 2>&1

Press ‘ESC’ and digit ‘:wq!’ to exit.

This is the actual result.

How to install Sphinx search engine in Snow Leopard, x86 and x86_64

sphinx
Sphinx is a free and open source SQL full-text search engine.
I assume you already have installed Xcode from Snow Leopard DVD.

First step is to download Sphinx, for this little guide we are going to use a beta.

cd into your favourite directory, mine is ‘src’ in my homedir.

cd src
curl -O http://www.sphinxsearch.com/downloads/sphinx-0.9.9-rc2.tar.gz

Decompress:

tar zxvf sphinx-0.9.9-rc2.tar.gz
cd sphinx-0.9.9-rc2/

For 32-bit users:

./configure --prefix=/usr/local

For 64-bit users:

LDFLAGS="-arch x86_64" ./configure --prefix=/usr/local

Remember that you can also specify sphinx to use MySQL this way, by appending this string to ./configure:

--with-mysql=/usr/local/mysql

or/and PostgreSQL

--with-pgsql

All users:

make
sudo make install

We are done.
If you encounter some errors, be sure to search for ‘mysql’ in this website, and follow the guide.

Having fun with MacRuby on Snow Leopard

macruby_logo
As the owner of the semi-official MacRuby github mirror I would like to introduce you MacRuby.

MacRuby is a Ruby bridge to Apple’s Cocoa/Objective-C that enables a developer to take fully advantage of the OS X frameworks while developing the application in Ruby programming language.

Quoting the official README:

MacRuby is a Ruby implementation based on Mac OS X technologies, such as the Objective-C runtime and garbage collector, the CoreFoundation framework and the LLVM compiler infrastructure.

Neat I’d say.

Let’s start by installing MacRuby (remember: you have to install Xcode from official Snow Leopard DVD if you want to compile from source).

Update: check out the MacRuby nightly builds.

First we need the LLVM trunk, and keep in mind that PowerPC is not supported.

Start by grabbing a stable version of LLVM from their svn server.

Update: the recommended LLVM revision is now 82747.

svn co -r 82747 https://llvm.org/svn/llvm-project/llvm/trunk llvm-trunk
cd llvm-trunk
./configure

Now you should know that compiling LLVM takes a long while.
To help speed up things you can take advantage of using two cores of your CPU, which is the case of the majority of the newer machines.

UNIVERSAL=1 UNIVERSAL_ARCH="i386 x86_64" ENABLE_OPTIMIZED=1 make -j2

However this can leave your machine in a sort of unresponsitive state, so if you prefer you can take away the “-j2″ parameter.

After your usual cup of coffee we can install LLVM with this command:

sudo env UNIVERSAL=1 UNIVERSAL_ARCH="i386 x86_64" ENABLE_OPTIMIZED=1 make install

Now we are ready to build MacRuby.

Start by cd-ing, if you’re not there already, into your preferred directory, we are going to use Git to download from trunk.

Update: instructions on how to install git on Snow Leopard are here.

git clone git://github.com/masterkain/macruby.git
cd macruby
rake
sudo rake install

That’s it.

Installing MacRuby won’t touch your existing ruby binaries, in fact it will install them prefixed with “mac”.
For instance you can open up MacRuby’s version of IRB with the command:

macirb  --simple-prompt

and start playing around.

There are other commands, just type “mac” and press tab in your terminal to see other binaries.

The very first thing to try out is to load a framework, namely ‘Cocoa’, so fire up your macirb and give it a try:

kain-osx:~ kain$ macirb
irb: warn: can't alias exit from irb_exit.
irb(main):001:0> framework 'Cocoa'
=> true
irb(main):002:0>

Go on and try loading an Objective-C class:

irb(main):002:0> NSSound.ancestors
=> [NSSound, NSObject, Kernel]

All classes in MacRuby always inherit from NSObject:

irb(main):003:0> Regexp.ancestors
=> [Regexp, NSObject, Kernel]

There are many things that are cool/exciting in this technology, for example take a look at this:

irb(main):004:0> String
=> NSMutableString

Uh. Seems like Ruby classes are mapped to their equivalents in Objective-C.
That’s right, and this happen with no data loss nor they require manual conversion!

One difference with RubyCocoa is that MacRuby supports keyed arguments, for instance:

MacRuby:

1
2
3
4
window = NSWindow.alloc.initWithContentRect frame, 
    styleMask:NSBorderlessWindowMask,
    backing:NSBackingStoreBuffered,
    defer:false

RubyCocoa:

1
2
3
4
5
window = NSWindow.alloc.initWithContentRect_styleMask_backing_defer(
    frame,
    NSBorderlessWindowMask,
    NSBackingStoreBuffered,
    false)

Objective-C:

1
2
3
4
5
NSWindow *window = [[NSWindow alloc]
    initWithContentRect:frame
    styleMask:NSBorderlessWindowMask
    backing:NSBackingStoreBuffered
    defer:false];

Let’s see how one can send message to our objects using MacRuby.
There are different syntaxes to accomplish this, let’s see some examples along with their Objective-C equivalent:

1
2
person.setName(name) # [person setName:name];
person.name = name # [person setName:name];

As we already said every class here inherits from NSObject, therefore is not necessary to explicitly define subclassing, like we did in RubyCocoa:

1
2
3
4
# RubyCocoa
class TestController < OSX::NSObject
# MacRuby
class TestController

Let’s build a very simple app to demonstrate that MacRuby works, open Xcode and choose New Project; from User Templates go into Application and select MacRuby Application, press “Choose..”.

A dialog will appear, give the application a name you prefer (“Hello World” will suit) and press Save. I usually save my project in a proper dedicated folder.

At this point Xcode will show you its main window, click on the left on “Other sources”.

You will see two files in there, main.m and rb_main.rb .
Xcode main interface
main.m is a small file which contains the method that calls the MacRuby initializer.
rb_main.rb is the ruby script that will be executed once your application started.

If you click on “Build and run” the application will start, showing you an empty window. cmd+Q for quitting the application.

Now click from the top menu File -> New file or just press cmd+N, from the left select “Other” and click on “Empty file”.
New file dialog

Press next and in the File name input write “MyController.rb”.
Controller generation

Press “Finish”.

If you see that MyController.rb on the left is floating around, just drag it into “Classes” folder. Be aware that Xcode folders doesn’t reflect the actual data structure on filesystem, but rather represent a logical approach.

Edit MyController.rb by selecting it and writing in the editor window:

1
2
3
4
5
6
  class MyController < NSWindowController
    attr_writer :button
    def clicked(sender)
      puts "Button clicked!"
    end
  end

Adding code

cmd+s to save the file.

Now, this code defines a subclass of NSWindowController and have two methods, a setter:

1
attr_writer :button

and clicked method:

1
def clicked(sender)

Those will serve the purpose especially with Interface Builder. In fact IB will see them respectively as an outlet and an action (for Obj-C users IBOutlet, IBAction).

To make sure that Interface Builder will pick up our method as an action, remember that it must have only one argument and that must be named sender.

We now have to wire our class with Interface Builder (from now on “IB”, go into the “Resources” folder and double click on MainMenu.nib .

In IB we need to instantiate our class to make it aware that we want to use one, to do that from the Library pane drag and drop a NSObject (blue cube) to the main window and select it.

From the inspector pane, as show in the next picture, select MyController as the Object Class.

ib

Now drag a NSButton always from the Library pane to your main window.
window

While having the just placed button selected Press CTRL and left click, this will make a line appear; place it over My Controller we defined earlier (blue cube) in your MainMenu.nib window.
When releasing the mouse a little hud-like menu will appear, named “Received Actions”.
Release the mouse when hovering “clicked:”.

That’s it, we made a connection from this button to our method in our MyController.

Save the Nib file, go back to Xcode and press “Build and run”.

Your application will start, showing a window and a button.
Leaving the application running let’s go back to xcode, and press the little icon on the right with “gdb” on it, this will open up the debugger window.

Now, leaving this window visible let’s try clicking on our button and see what happen.
If all went right we should see a bold “Button clicked!”.

That’s it for today, however there is much more to talk about, say HotCocoa.

For further documentation please refer to the official website of MacRuby project.