CONNECT

RVM is a critical part of your Ruby on Rails development stack. Why? Because it allows you to work in multiple Ruby environments. As soon as you build out more than one project you could find yourself having to deal with one project at a certain version of Ruby and another project at a different version. Without a tool like RVM. This can be a huge headache. Fortunately, installing RVM is pretty easy.

So let’s start on a bare OS X system. You’ll notice you have Ruby installed already by running the following command in the OS X Terminal App (all the commands in this post should be run in Terminal):

At the time of this post, the Ruby on my OS X 10.10 Yosemite was 2.0.0 patch level 481.

What you should be comfortable determining is whether or not you are seeing the OS X version of Ruby or the RVM version (the one you want).

So lets see the path to the ruby executable:

which ruby

Outputs:

/usr/bin/ruby

The output /usr/bin/ruby tells you that you are referencing the built in OS X ruby. Let’s fix that.

Here’s how you install RVM:

\curl -L https://get.rvm.io | bash -s stable --ruby

This could take some time to finish. When it does, run the previous command again to check your ruby executable path. It should read:

/Users/your-username/.rvm/rubies/ruby-2.1.3/bin/ruby

See that .rvm in the path? That means RVM is installed and being properly referenced!

The –ruby flag in the previous command installed the latest version of ruby. You can see that it has changed by checking for the version again:

ruby 2.1.3p242 (2014-09-19 revision 47630) [x86_64-darwin14.0]

Again, based on when you read this post and run these commands, your versions may be different.

Here are some default commands to get you started with RVM:

rvm list

This will show you the ruby executables (also called rubies) installed on your machine.

rvm list known

This will show you the rubies you can install

rvm install [insert ruby version number]

This will install a specific version of ruby to your machine

rvm install 2.0.0

rvm use [insert ruby version number] –default

This will make sure that a specific version of ruby is used every time you open a terminal window

rvm use 2.0.0 --default

rvm gemset list

This will list all the gemsets for your current ruby version

rvm gemset create [insert gemset name]

This will create a gemset in your current ruby version

rvm gemset create my-gemset

rvm use [insert ruby version number @ gemset name] –default

This will make sure a specific version of ruby is loaded every time AND at a specific gemset

rvm use 2.0.0@my-gemset

Now. What do you need to do in order to get started with Rails? Well, to be honest, there is some discussion as to whether or not gemsets are even required with Bundler. Obviously they are more important if you are developing a Ruby project without Bundler. So, for me, I find setting a ruby version is all I need.

Using RVM you have the ability to manage different ruby versions, what gems are included with each one and you’re not cluttering up the built in ruby with all your various project gems.

If you’re a Rails developer and you’re not using Postgres for your database, its likely because you have already invested time and energy installing and configuring MySQL on your Mac. You also probably got use to great tools like Sequel Pro for managing those databases also.

However, it seems the community has really moved towards Postgres. Why? Well I can’t say for everyone, but for me there were two big reasons:

Learning Rails can be daunting enough, but also learning how to do a production deployment of a Rails application can take it over the edge. To be honest, there really isn’t much of a reason to learn how to do a good production deployment of Rails unless you are personally responsible for taking client or company projects end to end – and even then, why wouldn’t you use Heroku, save yourself the liability of being responsible for managing a production Rails deployment. In my opinion, get really good at Rails. I’m not saying those server management skills aren’t important – I’m saying there are very important and just as specialized as learning Rails itself. So let someone who’s neck deep in operations take care of your app. End rant.

This doesn’t get talked about enough, but mobile introduced a huge new skill gap in developers. Those who know how to work with locations and those who don’t. What do I mean? Almost every mobile application has some location based feature. Well if you know mobile development then you are thinking: “That’s easy! iOS gives me the location of a user. done”. True, so does a web browser, that’s not the hard part. The hard part is asking whether that location is near another one… oh ya… you forgot about that part. Now there are a ton of ways to approach this, but PostGIS makes this a much easier task. Also, you think doing a production Rails deployment is hard… deploy a GIS product or server. No thanks.

So how do we install Postgres on OS X? Well there are a couple ways. Here’s the easy way. The way I do it.

Install the Postgres app

Go to http://postgresapp.com and click Download. Then drag that app to your Applications folder and fire it up. Done!

Its almost too simple.

So how do we use this with Rails? Well you will need the pg gem. When you try to install the gem you will likely get an error that it can’t find pg_config. That’s because its packaged in that cool app we just downloaded, so all you have to do is tell the gem where it is. Here’s how you do that:

Note: You may have to change the version number, but at the time of this post it was 9.3

Now you just fire up a rails project using:

rails new myapp --database=postgresql

Using a PostgreSQL Client on the Mac

That’s it! Now you could click that Open psql button and start managing your databases from the command line, and there is nothing wrong with that, but you might want a nice tool with an easy to use graphical interface. Unfortunately Sequel Pro… is MySQL only. So the best option I found is PGCommander. Its actually great, but its also $40. If you find something as good and cheaper let me know. I use PGCommander.

Enabling PostGIS for PostgreSQL

Remember the other thing I talked about? How cool PostGIS is. Well another great thing about that Postgres app is that its easily enabled if you are build some cool location based Rails web services!

To enable PostGIS, connect to your database and enter the command:

CREATE EXTENSION postgis;

So that’s it! Now you have a PostgreSQL database on OS X ready for development. You can easily start using PostGIS services if you need and you can manage the databases using PGCommander!

For the backend? I’m a rails (is it Rails?) developer. So I’ll use that. I’m gonna stub it out with hard-coded values to start… not really worrying about most of the backend until the end. I’ll push the app to Heroku so I can test it easily during development.

So what am I building? Well I have a couple ideas. I’m going to continue blogging my process and the problems I am hoping to solve, so maybe you’ll be able to figure it out… but for now… its a surprise.

Basically you have changed (uncommitted) files in your Homebrew working directory that you need to deal with. You simply need to reset the working directory so your update command can pull the latest files. If you’re familiar with git – then this will all make sense, if not, just run these 3 commands and your Homebrew will be fixed!

If you’re doing any Ruby on Rails or other open source development on your Mac, you’re going to need Homebrew.

What is Homebrew?

Homebrew is a package management system for your Mac. Homebrew makes it easy to install the software you generally need for Ruby on Rails development. Sometimes when you install RubyGems for your project, they will be dependent on software being installed on your Mac. One of the more obvious examples would be a MySQL gem and the actual MySQL Database Server. You install the MySQL Database Server using Homebrew! One of the less obvious examples would be the Nokogiri gem. This gem uses a software package named libxml2. You would install the libxml2 software package using Homebrew in order to install the Nokogiri RubyGem.

So how do you install Homebrew?

Installing Homebrew is dead simple. However, it does have a rather large dependency. You will need the command line tools addon of Xcode installed. Xcode is made by Apple and its used to write Mac and iOS applications. Xcode is free and all you need to do is search for it on the Mac App Store and click install. Its a rather large application, so it may take a while to download and install.

Once you’ve finished installing Xcode, you will need to install the command line tools.

Installing Command Line Tools on older versions of Xcode

You will need to open Xcode and choose Xcode -> Preferences. Choose the Downloads tab and install the Command Line Tools. If you don’t see any of this in Preferences, then read the next section…

This will take some time, but when its done your Mac will be ready to install Homebrew!

Install Command Line Tools on the latest version of Xcode

Open up a Terminal window. If you aren’t doing that by using Spotlight (which is how you should open ALL your Mac apps) then you do that by pressing CMD + SPACE, then searching ‘Terminal’. Hit Enter.

This command will need to be run in the OS X Terminal App. This means copy and pasting it into the Terminal window and pressing ENTER.

When the command is complete you should be able to run the following command in the Terminal window:

brew --version

If this works, then Homebrew is installed!

Now let’s go over a few common tasks you will have with Homebrew.

brew doctor

You want to use this command after system changes (such as OS X or Xcode updates) or if you think you need to troubleshoot your Homebrew installation. The output will tell you what’s wrong and generally how to fix it.

brew update

This will update your Homebrew formula list. Note, this doesn’t update all your installed packages! What this does is update the versions and availability of packages you could install. You want to run this often to keep your Homebrew installation up to date with the latest available software.

brew upgrade

This will upgrade your installed packages.

brew search [insert search term here]

This command will search the possible packages so you can find the one you want

brew install [insert package name here]

This will install a software package onto your system.

brew list

This will list all the packages that are currently installed on your system.

brew info [insert package name here]

Sometimes after you install a package, you get a screenful of information or configuration steps. If you’re like me, you will probably blow right past that and keep working – then it will dawn on you that you probably should have read some of that stuff. This will let you go back and do that.

brew uninstall [insert package name here]

And finally, you may want to remove a package you previously installed. That’s what this is for.

So that’s a quick intro to Homebrew and how you can manage software dependencies for RubyGems on your Mac!

I got this error today on my iMac. It was incredibly frustrating and I tried all of the following to fix it (the reason I list them is because I’m not entirely sure the final step I’ll mention at the end was the sole solution).

WOOHOO! It worked again! My hair is safe and I can stand down from Defcon 1. Why did this happen? I have no idea. Hopefully this helps someone else and please let me know in the comments if you know why this happened.

Rails 2.0 introduced protection for Cross-site request forgery (CSRF). This is turned on by default in your Rails applications. However, many developers are turning off this valuable protection rather than making the changes necessary to use it. This seems the same to me as leaving your door unlocked while your friend visits because cutting keys is hard. Case in point: text_field_with_auto_complete

You know you have run into the new CSRF protection when you see this error in your Rails application:

ActionController::InvalidAuthenticityToken

This is the point where you Google the error and receive one of the following pieces of advice:

1. Turn off RequestForgeryProtection all together

# add the following line to your application.rb or one of your# environment.rb files. why not production? (sarcasm)
config.action_controller.allow_forgery_protection = false

2. Turn off RequestForgeryProtection for just one controller

skip_before_filter :verify_authenticity_token

3. Turn off RequestForgeryProtection for just one action.

protect_from_forgery :except =&gt; :attack_me

So let’s see how easy it is to utilize this new feature!

I was working with the text_field_with_auto_complete in a pretty basic form:

For those of you who aren’t familiar with this there is a nice post on the Rails Wiki

When I tried to perform my auto complete I received the ActionController::InvalidAuthenticityToken error.

Why? Because basically my Ajax request did not include a security token that RequestForgeryProtection uses to validate my request is coming from the right place. All you need to do is add this token to the parameters sent with your request. Rails makes this easy with the helper: form_authenticity_token. The token name RequestForgeryProtection will be looking for is: authenticity_token.

So let’s add this to our text_field_with_auto_complete:

Now when I performed my auto complete it worked flawlessly! Now to refactor that string… any suggestions?

Update August 25, 2008

Learned two things working with this…

1. It’s automatically doing a POST, so by changing the method to GET I can avoid having to deal with the authenticity_token.

2. And with that out of the way I don’t need to specify the parameters since by default it will send back the value of the text field.

Ever since I saw Heroku I wanted to use it for a screencast on learning Ruby on Rails. This weekend I finished the very first episode! This episode is fairly light on Ruby on Rails content because I was so focused on screencasting and learning all about video and audio production for the web.

So take a look and tell me what you think. I used Vimeo for hosting the video. I also produced the video in HD… however I didn’t realize that Vimeo only streams the HD content on their site, not the embedded video. So to view the best possible video you should view it on Vimeo. here is the link. You can make it full screen and enjoy the HD in all its glory.

Please feel free to leave some constructive criticism regarding the screencast. This way I can make some changes before I start pushing this out more regularly.

I spend a lot of time convincing my friends to switch to a Mac. Some of my friends are also software developers so naturally, just when they think the evangelism has come to an end, I convince them to get on the Rails. However, learning Rails usually means learning Ruby for the first time as well. In this post I am going to address one of the issues I see for newcomers to Ruby. Looping.

Looping in Ruby seems to be a process of evolution for newcomers to the language. Newcomers will always find their way to the for loop almost immediately and when confronted with iterating an array, the first choice will generally be a for..in:

a = [1,2,3,4]
for n in a
puts n
end

This works, but its not very… Ruby. The next stage of evolution will be using an iterator for the first time. So the for loop gets dropped all together and each is used. The Rubyist is born at this point:

a.each do |n|
puts n
end

What I see next is a lot of conditional logic being used inside the each block. The logic is generally introduced to perform the following operations:

Building a list of items from an array.

Total the items in an array.

Find an item in the array.

So if this is you, then stop. Ruby has plenty more iterators where each came from. Which one you should be using depends on what operation you are trying to perform. So let’s take a look at our previous list and see if we can find a more Ruby way to get them done.

Building a list of items from the array using select

For this operation you should be using select. The way select works is simple, it basically iterates through all the elements in your array and performs your logic on each one. If the logic returns TRUE, then it adds the item to a new array which it returns when the iteration is complete. Here’s an example:

a = [1,2,3,4]
a.select {|n| n > 2}

This will return the last two elements in the array: 3 and 4. Why? Because 3 and 4 are both greater than 2, which was the logic we placed in the block. It’s worth noting that select has an evil step sister named reject. This will perform the opposite operation of select. Logic which returns FALSE adds the item to the array that is returned. Here’s the same examples as before except we will swap select, with reject:

a = [1,2,3,4]
a.reject {|n| n > 2}

In this example the return value is [1,2] because these elements return false when the condition is tested.

I also have to mention another close sibling to select and reject; collect, which returns an array of values that are the RESULT of logic in the block. Previously we returned the item based on the result of the CONDITION in the block. So perhaps we need square the values in our array:

a = [1,2,3,4]
a.collect {|n| n*n}

This returns a new array with each item in our array squared.

Finally, note that using select, reject, and collect returns an array. If you want to return something different, because you are concatenating or totaling values, then check out inject.

Total the items in an array using inject

When you think of accumulating, concatenating, or totaling values in an array, then think of inject. The main difference between select and inject is that inject gives you another variable for use in the block. This variable, referred to as the accumulator, is used to store the running total or concatenation of each iteration. The value added to the accumulator is the result of the logic you place in the block. At the end of each iteration, whatever that value is, can be added to the accumulator. For example, let’s sum all the numbers together in our array:

a = [1,2,3,4]
a.inject {|acc,n| acc + n}

This will return 10. The total value of all the elements in our array. The logic in our block is simple: add the current element to the accumulator. Remember, you must do something to the accumulator in each iteration. If we had simply placed n in the block the final value of the accumulator would have been 4. Why? Because its the last value in the array and since we did not add it to the accumulator explicitly the accumulator would be replaced in each iteration.

You can also use a parameter with the inject call to determine what the default value for the accumulator is:

a = [1,2,3,4]
a.inject(10) {|acc,n| acc + n}

In this example the result is 20 because we assigned the accumulator an initial value of 10.

If you need to return a string or an array from inject, then you will need to treat the accumulator variable that way. You can use the default value parameter of inject to do this:

a = [1,2,3,4]
a.inject([]) {|acc,n| acc << n+n}

In this example I add n to itself and then append it to the accumulator variable. I initialized the accumulator as an empty array using the default value parameter.

Find an item in the array using detect

Our last example operation was to find an element in the array. Let’s just put it out there and say that other iterators could be used to select the correct value from the array, but I am going to show you how to use detect to round out our exploration of these iterators.

So let’s find the value 3 in our array using detect:

a = [1,2,3,4]
a.detect {|n| n == 3}

This returns 3. The value we were looking for. If the value had not been found, then the iterator returns nil.

So if your head is spinning at this point as to which iterator to use for when, then remember this:

Use select or reject if you need to select or reject items based on a condition.

Use collect if you need to build an array of the results from logic in the block.

Use inject if you need to accumulate, total, or concatenate array values together.

Use detect if you need to find an item in an array.

By using these iterators you will be one step closer to mastering… Ruby-Fu.

There comes a time in every Rails developers life that they need to work with MySQL. Often this means that your development comes to a screeching halt as you wade through the various options for getting MySQL installed on your Mac.

This guide won’t help you install it anywhere else… because I am a zealot and I don’t care how to install it anywhere else.

Install MySQL using macports, go get a coffee while this runs its course.