Installing Ruby on Rails, Passenger, PostgreSQL, MySQL, Oh My Zsh on Snow Leopard, Fourth Edition
38 comments Latest by abercrombie clothes Thu, 18 Mar 2010 06:03:18 GMT
Welcome to what seems like my tenth installment (actually, it’s the fourth) of showing you how I setup my development environment on a fresh OSX install. In this case, I’m actually getting a MacBook setup for a new employee with Snow Leopard.
Over the years, I’ve evolved these following steps and they’ve helped our team maintain a consistent and stable envirnment for Ruby on Rails development. I know that there are a few other ways to approaching this and I’m sure you’ll get similar results, but this approach has allowed me to maintain a hassle-free setup for the last five years.
As with all things… your milage may vary.
Phase One
During this initial phase, we’re going to install the primary dependencies and setup our environment.
XCode
The first thing that you’ll need to do is install XCode, which almost everything depends upon as this will install developer-friendly tools for you. Apple has been kind enough to ship this on your Snow Leopard DVD.

Go ahead and install XCode from the Optional Installs folder.

(might require a reboot)
You can also download it online.
MacPorts
Now we’ll install MacPorts, which the web site describes itself as, “an open-source community initiative to design an easy-to-use system for compiling, installing, and upgrading either command-line, X11 or Aqua based open-source software on the Mac OS X operating system.”
As I’ve said in past versions of this guide, this tool is about to become one of the most important tools on your operating system. It’ll be used time and time again to maintain your libraries and many of the Unix tools that you’ll be using. If you’re from the Linux or BSD world, you are likely familiar with similar tools… such as: apt-get, port, and yum.
You’ll want to download the latest stable version from http://www.macports.org/. Once downloaded, you can install it.

Once this is installed, you’ll be able to use the port command from your console.
Wget
Let’s test out your MacPorts install by installing a useful tool called wget, which we’ll use to install oh-my-zsh.
sudo port install wget
Git and Subversion
Every development environment should have some source code management tools available. We’ll install both of these with one command.
sudo port install git-core +svn
This will install git and subversion.
oh-my-zsh
Oh My Zsh is the most amazing thing to happen to shells since… well since I said so. It’s one of my open source projects that I encourage you to give a whirl.
wget http://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | sh
That’s it. The next time you open up your terminal, you’ll be running zsh with a bunch of stuff available. For more information, visit http://github.com/robbyrussell/oh-my-zsh.
Terminal theme (optional)
I never understood why the icon for Terminal has a black background but when you start it up the default theme is black on white.

versus

Anyhow, I’m a fan of the the dark background. To change this, open up preferences in Terminal. Select Pro, then click on the Default window so that this sticks around.

Let’s now open up a new Terminal window..
You should be looking at something like this:

Much better… let’s continue.
Phase Two
We’re now going to start installing everything we need to get this running.
Ruby 1.8.7.x
First up, Ruby.
Snow Leopard includes Ruby and Rails already installed, but we’re going to back these up for a rainy day. Just issue these commands:
$ sudo su -
Password:
:~ root# mv /usr/bin/ruby /usr/bin/ruby.orig
:~ root# mv /usr/bin/gem /usr/bin/gem.orig
:~ root# mv /usr/bin/rails /usr/bin/rails.orig
:~ root# logout

Now we’ll go ahead and install a fresh copy of Ruby and RubyGems via MacPorts.
sudo port install ruby rb-rubygems
You should now see something like this for a bit…

Let’s watch a video about bumble bees.
When it finishes installing, you should check that Ruby is available to you and installed in /opt/local/bin.

We’ll also take a second to create a symlink for this as some tools seem to rely on /usr/bin/ruby being there.
sudo ln -s /opt/local/bin/ruby /usr/bin/ruby
Great, let’s move on.
Passenger (mod_rails)
Now that we have Ruby installed, we’re going to take a quick detour to setup Passenger with the Apache server already available on your machine. I’ve been a big fan of using Passenger for your development for over a year now.
sudo gem install passenger
Once the gem is finished installing, you’ll need to install the apache2 module with the following command:
It’ll ask you to continue by pressing Enter. At this point, it’ll check that you have all the necessary dependencies and then compile everything needed for Apache2.

Now I’ll force you to watch a highlights reel of Fernando Torres… the best striker in the world!
The passenger install will then show you this output, which you’ll want to stop and read for a moment and highlight the following:

Then using vi or emacs, you’ll want to create a new file with the following content:
vi /etc/apache2/other/passenger.conf
Then paste in the following (what you highlighted and copied above.)
LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.9
PassengerRuby /opt/local/bin/ruby
You’ll also want to include the following below what you just pasted.
# Set the default environment to development
RailsEnv development
# Which directory do you want Apache to be able to look into for projects?
<Directory "/Users/ryangensel/development">
Order allow,deny
Allow from all
</Directory>
You’ll want to quickly start up your web sharing, which will start Apache2 up via your System Preferences.


Simple enough… moving forward.
Passenger Pref Pane
To make things as simple as possible, I’d encourage you to install the Passenger Preference Pane (view this post for a download).

Development directory
I have a directory named development/ in my home directory, which is where I end up storing all of my projects. This should match whatever you put above in the apache configuration (<Directory "/Users/ryangensel/development">).
mkdir development; cd development;
Installing Ruby on Rails via RubyGems
Now we’ll use RubyGems to install the latest version of Ruby on Rails (and all of it’s dependencies).
sudo gem install rails

While this is installing, you can watch a video from my old band that ended around the time that business started picking up for Planet Argon.
Great, let’s test out the install of Rails…
Test Rails and Passenger
In your development directory, let’s quickly a new Rails app…
rails testapp
This will generate a new Rails application in a testapp/ directory.
Now open up the Passenger Preferences Pane and add this directory as a new application.


Press Apply…
You should now fire up your browser of choice and head to http://testapp.local. If all has worked, you’ll see a, “Welcome aboard” screen from the Ruby on Rails application.

Assuming that this worked for you, let’s take a quick break to make some tea…
Phase Three
In this last phase, we’re going to install a few database servers and corresponding rubygems so that you can get to work.
PostgreSQL
At Planet Argon, we build our web applications on top of PostgreSQL. I’ve been a long-time advocate of it and hope you consider using it yourself.
At this point in time, the current stable version of PostgreSQL via MacPorts is 8.4.x. Let’s install that now…
sudo port install postgresql84 postgresql84-server
Once this finishes compiling, you’ll need to run the following commands to setup a new PostgreSQL database.
sudo mkdir -p /opt/local/var/db/postgresql84/defaultdb
sudo chown postgres:postgres /opt/local/var/db/postgresql84/defaultdb
sudo su postgres -c '/opt/local/lib/postgresql84/bin/initdb -D /opt/local/var/db/postgresql84/defaultdb'
Assuming that you want PostgreSQL to always be running, you can run:
sudo launchctl load -w /Library/LaunchDaemons/org.macports.postgresql84-server.plist
...and to start it right now, run:
sudo launchctl start org.macports.postgresql84-server
Before you can start using it, we’ll need to make sure that the PostgreSQL executables are available in your shell path. Since you’re now using oh-my-zsh, you’ll want to edit ~/.zshrc with your favorite editor.
vi ~/.zshrc
Just append this to export PATH= line in the file.
:/opt/local/lib/postgresql84/bin
Your PATH might look something like the following now:
@# Customize to your needs… export PATH=/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/opt/local/lib/postgresql84/bin@
Setup database user
To setup a new database (with superuser credentials), just run:
createuser --superuser ryangensel -U postgres
We’ll now test creating a database:
createdb test_db
Let’s test that we can access it…
➜ ~ psql test_db
psql (8.4.2)
Type "help" for help.
test_db=# \q
Great, let’s drop it now.
➜ ~ dropdb test_db
➜ ~ psql test_db
psql: FATAL: database "test_db" does not exist
➜ ~
Okay, we’ll now install the library that will allow Ruby to talk to PostgreSQL.
Just run: sudo gem install pg

Voila… let’s move on to the inferior database…
MySQL
We’re going to run through the installation of MySQL really quickly because you might need it.
sudo port install mysql5 mysql5-server
This took ages on my machine… so let’s watch a video.
We’ll now setup the database and make sure it starts on system boot.
sudo -u _mysql mysql_install_db5
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist
sudo launchctl start org.macports.mysql5
Let’s test that we can create a database now (and that it’s running.)
➜ ~ mysql5 -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.1.43 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database test1;
Query OK, 1 row affected (0.00 sec)
mysql> \q
Great, we’ll now install the library that will allow Ruby to talk to MySQL.
sudo gem install mysql -- --with-mysql-config=/opt/local/lib/mysql5/bin/mysql_config
That should be it!
Phase Four, next steps
Okay… so we’ve installed XCode, MacPorts, Ruby, Rails, PostgreSQL, MySQL… and I’ve also got you to switch your default terminal shell from bash to zsh. You might take a look over the available themes for Oh My Zsh so that you can personalize your terminal experience even further.
You also now have a handful of gems installed as you can see with gem list.

Closing thoughts…
This is the fourth version of this guide and I’ve appreciated the hundreds of comments, questions, and emails that I have received… let’s not forget all those beers that people buy me when I’m at conferences. :-)
I hope you have found some of this useful. If you have any problems and/or questions, don’t hesitate to post them in the comments section below.
(oh my) Zsh themes Gone Wild! 18+
20 comments Latest by ed hardy clothing Wed, 17 Mar 2010 07:18:56 GMT
Earlier this evening, I accepted a pull-request for theme number 18, which is now included in Oh My Zsh. To celebrate, I’ve updated the themes wiki page with fresh screenshots.
Here is a sampling of some of the themes that you can use out of the box with Oh My Zsh.
Oh My Zsh is much more than a collection of themes for your zsh config. It’s a way of life1.
Also, be sure to follow ohmyzsh on twitter now!
1 well.. at least while you’re in the terminal. ;-)
Tracking Google Analytics events in development environment with GoogleAnalyticsProxy
20 comments Latest by shenhiujie Thu, 18 Mar 2010 08:02:45 GMT
As mentioned in a recent article1, I’ve been diving deep into Google Analytics lately while working on a few client projects. We’re aiming to use much more of the features of Google Analytics and have been hitting some roadblocks with the development versus production application environments. Once you begin to dive into event tracking and AJAX-driven goal conversions, relying on just the sample code that Google Analytics provides you is going to result in you looking at a handful of JavaScript errors.
another example from the firebug javascript console…
We see JavaScript errors like this because we don’t load the google analytics code in our development environments. As you can see, we are only loading this in our production environment.
<% if RAILS_ENV == 'production' -%>
<!--// Google Analytics //-->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-XXXXXX-1");
pageTracker._trackPageview();
</script>
<% end -%>To track an event with Google Analytics, you’d need to trigger something like:
pageTracker._trackEvent('Button', 'Click', 'Get in touch');As you can see from our code earlier, in development, the pageTracker variable isn’t defined and that’s why we’re getting those JS errors. We also don’t want to add conditionals everywhere in our application to check if we’re in development or production environment.. as that’d just make our views uglier than they need to be. So, I decided that I’d create a proxy class in JavaScript that would allow us to trigger _trackEvent() and _trackPageview() and handle it appropriately.
This class works with the following logic:
- if google analytics is loaded, pass the parameters to the real
pageTracker - if google analytics is NOT loaded, output the information to
console.log()for debugging purposes
For example, on a gallery on our web site… we track when people navigate next and/or previous through the photos. In our development environment, I can watch the JavaScript console output the following:
And in our production environment, we can see that this was sent to Google Analytics.
We’re able to do this by initializing the GoogleAnalyticsProxy class and calling these functions through it. For example:
_gap = new GoogleAnalyticsProxy();
_gap._trackEvent('Video', 'Play', 'Homepage video');
_gap._trackEvent('Video', 'Pause', 'Homepage video');
_gap._trackEvent('Button', 'Click', 'Call to action X');You’ll see that we’re just calling _gap versus pageTracker. We then replace all the instances of pageTracker (except where it is defined in the google analytics code block they provide you). You’ll find this located near the bottom of our application.html.erb file.
<% if RAILS_ENV == 'production' -%>
<!--// Google Analytics //-->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-XXXXXX-1");
pageTracker._trackPageview();
</script>
<% end -%>
<script type="text/javascript">
var _gap = new GoogleAnalyticsProxy();
</script>We now have _gap available throughout our project and can call _trackEvent() and _trackPageview() with it. Note: You can use any JS variable name that you want, _gap is just what I went with.
Get GoogleAnalyticsProxy
I’ve gone ahead and tossed this small JavaScript class (known as GoogleAnalyticsProxy) on Github for your enjoyment. I have some more articles in the works that will show you some tips for how to make the most of Google Analytics. If you have any questions and/or ideas for related article topics, don’t hesitate to let me know.
1 Tracking AJAX-driven events in Ruby on Rails for Google Analytics conversion goals
Flash Message Conductor now a Gem
6 comments Latest by replica pandora jewelryre Thu, 11 Mar 2010 06:22:40 GMT
We’ve been doing some early (or late… if you’re a half-full kind of person) spring cleaning on some of our projects. One of the small projects, flash_message_conductor, which we released last year as a plugin is now a gem. We’ve been moving away from using plugins in favor of gems as we like locking in specific released versions and being able to specify them in our environment.rb file is quite convenient.
To install, just run the following:
sudo gem install flash-message-conductor --source=http://gemcutter.org
Successfully installed flash-message-conductor-1.0.0
1 gem installed
Installing ri documentation for flash-message-conductor-1.0.0...
Installing RDoc documentation for flash-message-conductor-1.0.0...
You’ll then just need to include the following in your config/environment.rb file.
Rails::Initializer.run do |config|
# ...
config.gem 'flash-message-conductor', :lib => 'flash_message_conductor', :source => "http://gemcutter.org"
endYou can take a peak at the README for usage examples.
We’ll be packaging up a handful of our various plugins that we reuse on projects and moving them to gems. Stay tuned… :-)
Planting the seeds
27 comments Latest by abercrombie clothes Thu, 18 Mar 2010 06:07:17 GMT
Yesterday, the Rails team released 2.3.4, which includes standardized way for loading seed data into your application so that you didn’t have to clutter your database migrations.
I noticed a few comments on some blogs where people were asking how to use this new feature, so here is a quick runthrough a few ways that you can use it.
Populating Seed Data Approaches
The db/seeds.rb file is your playground. We’ve been evolving our seed file on a new project and it’s been great at allowing us to populate a really large data. Here are a few approaches that we’ve taken to diversify our data so that when we’re working on UI, we can have some diversified content.
Basic example
Any code that add to db/seeds.rb is going to executed when you run rake db:seed. You can do something as simple as:
# db/seeds.rb
Article.create(:title => 'My article title', :body => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit')Just create database records like you would in your Rails application or in script/console. Simple enough, right? Let’s play with a few other approaches that we’ve begun to use.
Use the names of real people
We’re using the Octopi gem to connect to github, collect all the names of people that follow me there, and using their names to seed our development database.
@robby_on_github = Octopi::User.find('robbyrussell')
# add a bunch of semi-real users
@robby_on_github.followers.each do |follower|
github_person = Octopi::User.find(follower)
next if github_person.name.nil?
# split their name in half... good enough (like the goonies)
first_name = github_person.name.split(' ')[0]
last_name = github_person.name.split(' ')[1]
new_person = Person.create(:first_name => first_name, :last_name => last_name, :email => Faker::Internet.email,
:password => 'secret', :password_confirmation => 'secret',
:github_username => follower, :website_url => github_person.blog)
# ...
endWe do this with a few sources (twitter, github, etc..) to pull in the names of real people. If you want to be part of my seed data, you might consider following me on Github. ;-)
Use Faker for Fake data
You may have noticed in the previous code sample, that I used Faker in that code. We are using this a bunch in our seed data file. With Faker, you can generate a ton of fake data really easy.
person.links.create(:title => Faker::Lorem.words(rand(7)+1).join(' ').capitalize,
:url => "http://#{Faker::Internet.domain_name}/",
:description => Faker::Lorem.sentences(rand(4)+1).join(' '))We might toss something like that into a method so that we can do the following:
@people = Person.find(:all)
500.times do
generate_link_for(@people.sort_by{rand}[0])
end...and we’ll get 500 links added randomly across all of the people we added to our system. You can get fairly creative here.
For example, we might even wanted random amounts of comments added to our links.
def generate_link_for(person)
link = person.links.create(:title => Faker::Lorem.words(rand(7)+1).join(' ').capitalize,
:url => "http://#{Faker::Internet.domain_name}/",
:description => Faker::Lorem.sentences(rand(4)+1).join(' '))
# let's randomly add some comments...
if link.valid?
rand(5).times do
link.comments.create(:person_id => @people.sort_by{rand}[0].id,
:body => Faker::Lorem.paragraph(rand(3)+1))
end
end
endIt’s not beautiful, but it gets the job done. It makes navigating around the application really easy so that we aren’t having to constantly input new data all the time. As mentioned, it really helps when we’re working on the UI.
Your ideas?
We’re trying a handful of various approaches to seed our database. If you have some fun ways of populating your development database with data, we’d love to hear about it.
..and on the seventh day, Science created zsh
9 comments Latest by ed hardy clothing Wed, 17 Mar 2010 07:35:07 GMT
Inspired by some recent posts from Tom on zsh, I decided that I’d do my part to help people give it a whirl. I’ve been using zsh for a few years now and haven’t found myself missing bash.
If you’re interested in taking a few minutes to give zsh a while, you’re in luck. I recently reorganized all of my zsh config into a package and tossed it on github to share. My goal was to create a reusable tool that would allow people to get up and running quickly with some of the fun configuration that I’ve come to rely on on a daily basis.
For example:
- Auto-complete rake and capistrano tasks
- Git branch names when you’re in a git project directory structure
- Tons of color highlighting (grep, git, etc.)
- Sexy prompts.. (so say me)
- much much more…
I invite you to give Oh My Zsh a whirl, which should take you less than a minute. Just follow the instructions.
Also, Oh My Zsh is Snow Leopard compatible. ;-)










