<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>MetaGreg</title>
	
	<link>http://gregmoreno.ca</link>
	<description>writes code that writes code for food</description>
	<lastBuildDate>Thu, 02 Sep 2010 00:20:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/gregmoreno" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="gregmoreno" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">gregmoreno</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Deploy a Rails 3, Sqlite3 application in Tomcat using JRuby</title>
		<link>http://gregmoreno.ca/deploy-a-rails-3-sqlite3-application-in-tomcat-using-jruby/</link>
		<comments>http://gregmoreno.ca/deploy-a-rails-3-sqlite3-application-in-tomcat-using-jruby/#comments</comments>
		<pubDate>Thu, 02 Sep 2010 00:08:42 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Geekiness]]></category>
		<category><![CDATA[jruby]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[tomcat]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=839</guid>
		<description><![CDATA[and have a Ruby version running side-by-side. A few months ago I got interested in JRuby while researching for text mining algorithms. I found some gems but they are either unmaintained or inadequate while the mature libraries I found were written in Java. No problem! JRuby to the rescue. Thank God. Next stop, I decided [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 1: Booting the application'>Rails 3 upgrade part 1: Booting the application</a> <small>It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live...</small></li>
<li><a href='http://gregmoreno.ca/how-to-setup-a-rails-3-app/' rel='bookmark' title='Permanent Link: How to setup a Rails 3 app'>How to setup a Rails 3 app</a> <small>I finally decided to give Rails 3 a spin after beta was released 20 days ago. In geek time, that&#8217;s being a late adopter. But first, a warning. I&#8217;ve read...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 4: Prototype helpers and Javascript'>Rails 3 upgrade part 4: Prototype helpers and Javascript</a> <small>Rails 3 is embracing the unobtrusive Javascript (or UJS) mantra which is good because it is the right way; at the same time, it is bad because many applications will...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><em>and have a Ruby version running side-by-side.</em></p>
<p>A few months ago I got interested in <a href="http://jruby.org/">JRuby</a> while researching for <a href="http://alias-i.com/lingpipe/">text mining algorithms</a>. I found some gems but they are either unmaintained or inadequate while the mature libraries I found were written in Java. No problem! JRuby to the rescue. Thank God.</p>
<p>Next stop, I decided to take Rails 3 and JRuby for a spin. Incidentally, I will be on a <a href="http://railsjam.net">3-city Rails tour in the Philippines</a> this September  and since there are many<a href="http://tech.groups.yahoo.com/group/pinoyjug/"> Filipino Java developers</a>, they might find it interesting to see their favorite Java platform works nicely with Ruby on Rails.</p>
<p><strong>Setup</strong></p>
<p>I will be using the following for this tutorial:</p>
<pre class="brush: bash;">
java 1.6 + JDK
tomcat 7.0.2
rvm 1.0.1
jruby 1.5.0
ruby 1.9.2p0
</pre>
<p>Further below, I outline how to install these software. First, let’s see my current environment.</p>
<pre class="brush: bash;">
$ more /etc/issue
Ubuntu 9.10 \n \l

$ java -version
java version &quot;1.6.0_20&quot;
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) Server VM (build 16.3-b01, mixed mode)

$ rvm -v
rvm 1.0.1 by Wayne E. Seguin (wayneeseguin@gmail.com) [http://rvm.beginrescueend.com/]

$ jruby -v
jruby 1.5.0 (ruby 1.8.7 patchlevel 249) (2010-05-12 6769999) (Java HotSpot(TM) Client VM 1.6.0_20) [i386-java]

$ TOMCAT/bin/version.sh
Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.2
Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.2
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.2/temp
Using JRE_HOME:        /usr
Using CLASSPATH:       /usr/local/apache-tomcat-7.0.2/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.2/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.2
Server built:   Aug 4 2010 12:23:47
Server number:  7.0.2.0
OS Name:        Linux
OS Version:     2.6.31-22-generic
Architecture:   i386
JVM Version:    1.6.0_20-b02
JVM Vendor:     Sun Microsystems Inc.

$ ruby -v
ruby 1.9.2p0 (2010-08-18 revision 29036) [i686-linux]
</pre>
<p><strong>Install JDK and Tomcat</strong></p>
<pre class="brush: bash;">
$ aptitude install curl sun-java6-bin sun-java6-jre sun-java6-jdk
$ wget  http://apache.mobiles5.com/tomcat/tomcat-7/v7.0.2-beta/bin/apache-tomcat-7.0.2.tar.gz
$&gt; tar zxvf apache-tomcat-7.0.2.tar.gz
$&gt; mv apache-tomcat-7.0.2 /usr/local
</pre>
<p>Of course, these assume you want to use 7.0.2 and you want it installed at your /usr/local.</p>
<p><strong>Install JRuby, Rails 3</strong></p>
<p>I assume you already have <a href="http://rvm.beginrescueend.com/">rvm</a> installed. If not, I highly recommend that you do. I can’t imagine a Ruby developer not using rvm :)</p>
<pre class="brush: bash;">
$ rvm install jruby
$ rvm jruby
$ rvm gemset create railsjam
$ rvm jruby@railsjam
$ gem install rails
</pre>
<p><strong>Try a sample app</strong></p>
<p>I’ve created  sample app for the<a href="http://railsjam.net"> RailsJam tour</a>. This have several functionalities already and better than creating a Rails app from scratch.</p>
<pre class="brush: bash;">
$ git clone git://github.com/gregmoreno/railsjam.git
</pre>
<p><strong>Update the Gemfile</strong></p>
<p>You need a separate set of gems to make your Rails 3 application work with JRuby. For learning purposes, I want my Rails 3 application to work other than JRuby. To accomplish that, we need to specify what gems are needed solely by JRuby.</p>
<pre class="brush: ruby;">
source 'http://rubygems.org'

gem 'rails', '3.0.0'

if defined?(JRUBY_VERSION)
  gem 'jdbc-sqlite3'
  gem 'activerecord-jdbc-adapter'
  gem 'activerecord-jdbcsqlite3-adapter'
  gem 'jruby-openssl'
  gem 'jruby-rack'
  gem 'warbler'
else
  gem 'sqlite3-ruby', :require =&gt; 'sqlite3'
end
</pre>
<p>(A copy of this Gemfile is available at the ‘jruby’ folder of the railsjam application.)</p>
<p>Now, it’s time to intall the gems.</p>
<pre class="brush: bash;">
# Must do this. Otherwise,  bundle picks up wrong version of jdbc
$ rm Gemfile.lock
$ jruby -S bundle install
</pre>
<p><strong>Prepare the database.</strong></p>
<p>The first time I worked on this tutorial, I needed to specify the jdbcsqlite3 as the database adapter. However, when I tried the tutorial on the same machine with a fresh gemset, it worked pretty well with just ‘sqlite3’.  Just to be sure, I modified  ‘database.yml’ to check for JRuby.</p>
<pre class="brush: ruby;">
development:
  adapter: &lt;%= defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' %&gt;
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: &lt;%= defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' %&gt;
  database: /home/greg/dev/railsjam/db/development.sqlite3
  pool: 5
  timeout: 5000
</pre>
<p>When you deploy to Tomcat, it will be on ‘production’ mode by default. Since sqlite3 is file based and for simplicity, I used the same development database.</p>
<p>Now, do the migration.</p>
<pre class="brush: bash;">
$ jruby -S rake db:migrate
</pre>
<p><strong>Deploy to Tomcat</strong></p>
<p>We use ‘<a href="http://caldersphere.rubyforge.org/warbler/">warble</a>’ which is an excellent tool for packaging your Rails application. It packages everything you need to run your Rails application inside a Java container.</p>
<pre class="brush: bash;">
$ warble
$ cp railsjam.war  $TOMCAT/webapps

# start Tomcat
# assuming you arein $TOMCAT dir
$ sudo ./startup.sh
</pre>
<p><strong>Check your Rails 3 application</strong></p>
<pre class="brush: bash;">
# You should see the famous Rails welcome
localhost:3000/railsjam

# Play around with your application
localhost:3000/railsjam/users
</pre>
<p><strong>Deploy Rails 3 using Ruby 1.9.2 </strong></p>
<p>Without shutting down your JRuby and Tomcat version, let’s try to run our app using Ruby 1.9.2</p>
<pre class="brush: bash;">
# In a new console
$ rvm 1.9.2
$ rvm gemset create railsjam
$ rvm 1.9.2@railsjam
$ gem install rails

# Assuming you are in the ‘railsjam’ folder
# This will install sqlite3-ruby gem
$ bundle install

$ rails server
</pre>
<p>Now, go play with your Rails 3 applications</p>
<pre class="brush: bash;">
# jruby + tomcat

http://localhost:8080/railsjam/users

# ruby 1.9.2

http://localhost:3000/users
</pre>
<p>In case you encountered some problems, here are some ways to solve them. If your problem is not listed here, you can email me. I only accept Paypal :)</p>
<p><strong>JRuby does not support native extensions</strong></p>
<p>You did not update the Gemfile to use the jdbc version of sqlite3. You will encounter this error when you install the gems.</p>
<pre class="brush: bash;">
$ bundle install
....
Installing sqlite3-ruby (1.3.1) with native extensions /home/greg/.rvm/rubies/jruby-1.5.2/lib/ruby/site_ruby/1.8/rubygems/installer.rb:482:in `build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/home/greg/.rvm/rubies/jruby-1.5.2/bin/jruby extconf.rb
WARNING: JRuby does not support native extensions or the `mkmf' library.
         Check http://kenai.com/projects/jruby/pages/Home for alternatives.
extconf.rb:9: undefined method `dir_config' for main:Object (NoMethodError)
</pre>
<p><strong>undefined method `attributes_with_quotes&#8217; for class `ActiveRecord::Base&#8217;</strong></p>
<p>I first encountered this problem when doing migration.</p>
<pre class="brush: bash;">
$ rake db:migrate
rake aborted!
undefined method `attributes_with_quotes' for class `ActiveRecord::Base'
</pre>
<p>This is caused by an old version of your jdbc gems. In my case, sometimes bundler installs the old versions:</p>
<pre class="brush: bash;">
Installing activerecord-jdbc-adapter (0.9.2)
Installing activerecord-jdbcsqlite3-adapter (0.9.2)
</pre>
<p>As of this writing, the latest version is 0.9.7</p>
<pre class="brush: bash;">
Installing activerecord-jdbc-adapter-0.9.7-java
Installing activerecord-jdbcsqlite3-adapter-0.9.7-java
</pre>
<p><strong>Bundler keeps installing 0.9.2</strong></p>
<pre class="brush: bash;">
$ rm Gemfile.lock
$ jruby -S bundle install
</pre>
<p><strong>no such file to load &#8212; sqlite3</strong></p>
<pre class="brush: bash;">
$ rake db:migrate
(in /home/greg/dev/projects/jruby/railsjam)
rake aborted!
no such file to load -- sqlite3
</pre>
<p>‘sqlite3’ is the default name of the database adapter but with jruby, it should be ‘jdbcsqlite3’.  (another) But, when I tried ‘sqlite3’ with a fresh gemset and a new machine, it went well. Anyway, just in case you run into the same problem in the future, add a condition in your database.yml </p>
<pre class="brush: ruby;">
development:
  adapter: &lt;%= defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' %&gt;
  database: db/development.sqlite3
  pool: 5
  timeout: 5000
</pre>
<p><strong>We&#8217;re sorry, but something went wrong.</strong></p>
<p>If you see the famous Rails error message, you need to dig in Tomcat’s log files.</p>
<pre class="brush: bash;">
$ cd /usr/local/apache-tomcat-7.0.2/logs
$ ls -al localhost*

-rw-r--r-- 1 root root 1181 2010-09-01 00:17 localhost.2010-09-01.log
-rw-r--r-- 1 root root 1062 2010-09-01 00:18 localhost_access_log.2010-09-01.txt

$ tail -f localhost.2010-09-01.log
</pre>
<p>In the log file, you will see the errors like missing database.</p>
<p>org.jruby.rack.RackInitializationException: The driver encountered an error: java.sql.SQLException: path to &#8216;/home/greg/dev/tmp/apache-tomcat-7.0.2/webapps/railsjam/WEB-INF/db/production.sqlite3&#8242;: &#8216;/home/greg/dev/tmp/apache-tomcat-7.0.2/webapps/railsjam/WEB-INF/db&#8217; does not exist</p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 1: Booting the application'>Rails 3 upgrade part 1: Booting the application</a> <small>It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live...</small></li>
<li><a href='http://gregmoreno.ca/how-to-setup-a-rails-3-app/' rel='bookmark' title='Permanent Link: How to setup a Rails 3 app'>How to setup a Rails 3 app</a> <small>I finally decided to give Rails 3 a spin after beta was released 20 days ago. In geek time, that&#8217;s being a late adopter. But first, a warning. I&#8217;ve read...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 4: Prototype helpers and Javascript'>Rails 3 upgrade part 4: Prototype helpers and Javascript</a> <small>Rails 3 is embracing the unobtrusive Javascript (or UJS) mantra which is good because it is the right way; at the same time, it is bad because many applications will...</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/xVI2JX_tC_ssOkhLTIfn577pW_c/0/da"><img src="http://feedads.g.doubleclick.net/~a/xVI2JX_tC_ssOkhLTIfn577pW_c/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/xVI2JX_tC_ssOkhLTIfn577pW_c/1/da"><img src="http://feedads.g.doubleclick.net/~a/xVI2JX_tC_ssOkhLTIfn577pW_c/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/deploy-a-rails-3-sqlite3-application-in-tomcat-using-jruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails 3 upgrade part 4: Prototype helpers and Javascript</title>
		<link>http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/</link>
		<comments>http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 01:44:43 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Geekiness]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=829</guid>
		<description><![CDATA[Rails 3 is embracing the unobtrusive Javascript (or UJS) mantra which is good because it is the right way; at the same time, it is bad because many applications will break when they upgrade to Rails 3. On the other hand, who&#8217;s expecting a smooth upgrade anyway :) In my test application, I used jrails [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 3: Code fixes, views, and forms'>Rails 3 upgrade part 3: Code fixes, views, and forms</a> <small>This is part 3 of my Rails 2 to Rails 3 upgrade experience. Part 1 is about the initial code upgrade and getting the application to boot while part 2...</small></li>
<li><a href='http://gregmoreno.ca/how-to-share-code-between-javascript-and-rails/' rel='bookmark' title='Permanent Link: How to share code between Javascript and Rails'>How to share code between Javascript and Rails</a> <small>Rails&#8217; validations is great because it allows you to quickly implement the valid states of your models and at the same time have a ready-made way of displaying the errors...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-2-routes/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 2: Routes'>Rails 3 upgrade part 2: Routes</a> <small>In the previous post, I outlined the steps I took to upgrade and boot a Rails 3 application. This time, I share my experience upgrading the routes file. By the...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Rails 3 is embracing the <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript">unobtrusive Javascript (or UJS)</a> mantra which is good because it is the right way; at the same time, it is bad because many applications will break when they upgrade to Rails 3. On the other hand, who&#8217;s expecting a smooth upgrade anyway :)</p>
<p>In my test application, I used jrails because I am more interested in jQuery than Prototype. But since <a href="http://www.railsplugins.org/plugins/264-jrails">jrails doesn&#8217;t work with Rails 3</a>, I removed it.</p>
<p>When jrails was removed, I received this error:</p>
<pre class="brush: ruby;">
undefined method `observe_field' for #&lt;#&lt;Class:0xb6867e58&gt;:0xb6865b6c&gt;
</pre>
<p><strong>Install Prototype helper plugin</strong></p>
<p>&#8216;<a href="http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/observe_field">observe_field&#8217; is a Prototype helper</a> and Rails 3 removed the the link between its Javascript helpers and Prototype. The goal in Rails 3 is for developers to use their preferred Javascript library. Also note that  remote_#{method} helpers have been removed from Rails and moved to <a href="http://github.com/rails/prototype_legacy_helper">Prototype Legacy Helper plugin</a> . To install this plugin, just do:</p>
<pre class="brush: plain;">
rails plugin install git://github.com/rails/prototype_legacy_helper
</pre>
<p><strong>Remove jQuery</strong></p>
<p>Once the prototype_legacy_helper is installed, the missing method is gone but observe_field is not triggering. Removing jQuery fixes this problem.</p>
<p>Now what if you want to use jQuery instead of Prototype? It depends how dependent your application is to Prototype. I have not found a jQuery equivalent for Prototype helper plugin yet so that would be an issue like in my case. Based on this <a href="http://blog.bernatfarrero.com/jquery-and-rails-3-mini-tutorial/">jQuery and Rails 3 tutorial</a>, using the jQuery UJS driver looks very easy. </p>
<p>Previous: <a href="http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/">Rails 3 upgrade part 3: Code fixes, views, and forms</a></p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 3: Code fixes, views, and forms'>Rails 3 upgrade part 3: Code fixes, views, and forms</a> <small>This is part 3 of my Rails 2 to Rails 3 upgrade experience. Part 1 is about the initial code upgrade and getting the application to boot while part 2...</small></li>
<li><a href='http://gregmoreno.ca/how-to-share-code-between-javascript-and-rails/' rel='bookmark' title='Permanent Link: How to share code between Javascript and Rails'>How to share code between Javascript and Rails</a> <small>Rails&#8217; validations is great because it allows you to quickly implement the valid states of your models and at the same time have a ready-made way of displaying the errors...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-2-routes/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 2: Routes'>Rails 3 upgrade part 2: Routes</a> <small>In the previous post, I outlined the steps I took to upgrade and boot a Rails 3 application. This time, I share my experience upgrading the routes file. By the...</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/kbRVr5-W8MwfjlfjBkCtzbIl-Jo/0/da"><img src="http://feedads.g.doubleclick.net/~a/kbRVr5-W8MwfjlfjBkCtzbIl-Jo/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/kbRVr5-W8MwfjlfjBkCtzbIl-Jo/1/da"><img src="http://feedads.g.doubleclick.net/~a/kbRVr5-W8MwfjlfjBkCtzbIl-Jo/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rails 3 upgrade part 3: Code fixes, views, and forms</title>
		<link>http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/</link>
		<comments>http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/#comments</comments>
		<pubDate>Sat, 14 Aug 2010 00:12:36 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=814</guid>
		<description><![CDATA[This is part 3 of my Rails 2 to Rails 3 upgrade experience. Part 1 is about the initial code upgrade and getting the application to boot while part 2 deals with routes. While Part 2 is mainly about routes, getting it work involved changes in other parts of the code which I&#8217;ll share this [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-2-routes/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 2: Routes'>Rails 3 upgrade part 2: Routes</a> <small>In the previous post, I outlined the steps I took to upgrade and boot a Rails 3 application. This time, I share my experience upgrading the routes file. By the...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 4: Prototype helpers and Javascript'>Rails 3 upgrade part 4: Prototype helpers and Javascript</a> <small>Rails 3 is embracing the unobtrusive Javascript (or UJS) mantra which is good because it is the right way; at the same time, it is bad because many applications will...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 1: Booting the application'>Rails 3 upgrade part 1: Booting the application</a> <small>It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>This is part 3 of my Rails 2 to Rails 3 upgrade experience. Part 1 is about the initial code upgrade and <a href="http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/">getting the application to boot</a> while <a href="http://gregmoreno.ca/rails-3-upgrade-part-2-routes/">part 2 deals with routes</a>. While Part 2 is mainly about routes, getting it work involved changes in other parts of the code which I&#8217;ll share this time. So while you are updating your routes, you may need to check this post in between changes.</p>
<p><strong>Update ApplicationController</strong></p>
<p>After regenerating your application with rails (i.e. rails new appname -d dbadapter), your ApplicationController would look like this:</p>
<pre class="brush: ruby;">
class ApplicationController &lt; ActionController::Base
  protect_from_forgery
end
</pre>
<p>There&#8217;s no need to panic because rails:upgrade:backup made a copy of the controller to application_controller.rb.rails2.</p>
<p>If you have a lot of helper modules, you&#8217;ll most likely have this code in your Rails 2 ApplicationController:</p>
<pre class="brush: ruby;">
helper :all
</pre>
<p>If you encounter a missing method error while monkey clicking your application, you probably forgot to update your Rails 3 ApplicationController.</p>
<p><strong>Update ApplicationHelper</strong></p>
<p>The ApplicationHelper module was also modified by the rails upgrde. So don&#8217;t forget to update this, too.</p>
<p><strong>RAILS_* constants are deprecated is not entirely true</strong></p>
<p>When you run rails:upgrade:check, it will list items you need to update including deprecated code. There is no need to change these as the word &#8216;deprecated&#8217; means but I encountered several &#8220;can&#8217;t convert nil into String&#8221; errors. </p>
<pre class="brush: bash;">
rake rails:upgrade:check
(in /mnt/hgfs/greg-mini/dev/projects/propsify)
Deprecated constant(s)
Constants like RAILS_ENV, RAILS_ROOT, and RAILS_DEFAULT_LOGGER are now deprecated.
More information: http://litanyagainstfear.com/blog/2010/02/03/the-rails-module/

The culprits:
  ...
</pre>
<p>The weird part is some constants are just doing fine.  In any case, here are the conversion:</p>
<pre class="brush: plain;">
RAILS_ROOT  -&gt; Rails.root
RAILS_ENV -&gt; Rails.env
RAILS_DEFAULT_LOGGER -&gt; Rails.logger
</pre>
<p>You can also check your environment the Ruby way:</p>
<pre class="brush: ruby;">
# before
if RAILS_ENV == 'production'
  ...

# Rails 3
if Rails.env.production?
</pre>
<p><strong>Output strings are automatically escaped</strong></p>
<p>We should all be rejoicing that Rails is now serious about XSS protection except now your pages have become ugly with all those HTML tags. For example the code below will not give you a clickable link.</p>
<pre class="brush: ruby;">
- signup = link_to('create one here', signup_path)
= &quot;If you do not have an account, #{signup}.&quot;
</pre>
<p>To fix this, use the raw() helper.</p>
<pre class="brush: ruby;">
= raw &quot;If you do not have an account, #{signup}.&quot;
</pre>
<p>Too bad for me, I got tons of views that were coded like this.</p>
<p><strong>Check for &#8216;concat&#8217;</strong></p>
<p>A popular technique to simplify your view code is to use content blocks. You create a helper that takes a block and wraps it in some HTML tags. A simple implementation would look like this:</p>
<pre class="brush: ruby;">
module LayoutHelper
  def main_column(options={}, &amp;block)
    # calls column()
  end

  def column(options={}, &amp;block)
    # concat is not needed in Rails 3
    concat content_tag(:div, capture(&amp;block), options)
  end
end

# in your view
- main_column do
  = render 'form'
</pre>
<p>This works fine in Rails 2 but in Rails 3 the block gets outputted twice. <a href="http://apidock.com/rails/ActionView/Helpers/TextHelper/concat">concat</a> is the way to output text in a non-output block (i.e. &lt;% %&gt; in erb) but it seems like <a href="http://asciicasts.com/episodes/208-erb-blocks-in-rails-3">erb blocks in Rails 3 do not need concat</a>.</p>
<p><strong>Helpers with blocks</strong></p>
<p>Before Rails 3, form_for or fields_for use non-output syntax; it means no equals sign. </p>
<pre class="brush: ruby;">
# erb
&lt;% form_for @offer do |f| %&gt;
  # ...
&lt;% end %&gt;

# haml
- form_for @offer do |f|
  # ...
</pre>
<p>In Rails 3, it should now be written as an output block.</p>
<pre class="brush: ruby;">
# erb
&lt;%= form_for @offer do |f| %&gt;
  # ...
&lt;% end %&gt;

# haml
= form_for @offer do |f|
  = f.fields_for :items do |ff|
    # ...
</pre>
<p>The rule is if the method is expected to return a string, it should use the output syntax. If it just <a href="http://edgeguides.rubyonrails.org/3_0_release_notes.html">buffering the returned string like content_for, it should NOT have the equals sign</a>.</p>
<p>Previous: <a href="http://gregmoreno.ca/rails-3-upgrade-part-2-routes/">Rails 3 upgrade part 2: Routes</a><br />
Next: <a href="http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/">Rails 3 upgrade part 4: Prototype helpers and Javascript</a></p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-2-routes/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 2: Routes'>Rails 3 upgrade part 2: Routes</a> <small>In the previous post, I outlined the steps I took to upgrade and boot a Rails 3 application. This time, I share my experience upgrading the routes file. By the...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 4: Prototype helpers and Javascript'>Rails 3 upgrade part 4: Prototype helpers and Javascript</a> <small>Rails 3 is embracing the unobtrusive Javascript (or UJS) mantra which is good because it is the right way; at the same time, it is bad because many applications will...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 1: Booting the application'>Rails 3 upgrade part 1: Booting the application</a> <small>It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live...</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/ehL_MA8Bx9VYCyQNiAD-65r59ZA/0/da"><img src="http://feedads.g.doubleclick.net/~a/ehL_MA8Bx9VYCyQNiAD-65r59ZA/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/ehL_MA8Bx9VYCyQNiAD-65r59ZA/1/da"><img src="http://feedads.g.doubleclick.net/~a/ehL_MA8Bx9VYCyQNiAD-65r59ZA/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rails 3 upgrade part 2: Routes</title>
		<link>http://gregmoreno.ca/rails-3-upgrade-part-2-routes/</link>
		<comments>http://gregmoreno.ca/rails-3-upgrade-part-2-routes/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 21:40:05 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Geekiness]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=787</guid>
		<description><![CDATA[In the previous post, I outlined the steps I took to upgrade and boot a Rails 3 application. This time, I share my experience upgrading the routes file. By the way, I forgot to mention in the last post that I&#8217;m using Rails 3 Upgrade Handbook by Jeremy McAnally. The task rails:upgrade:routes (comes with the [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 4: Prototype helpers and Javascript'>Rails 3 upgrade part 4: Prototype helpers and Javascript</a> <small>Rails 3 is embracing the unobtrusive Javascript (or UJS) mantra which is good because it is the right way; at the same time, it is bad because many applications will...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 1: Booting the application'>Rails 3 upgrade part 1: Booting the application</a> <small>It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 3: Code fixes, views, and forms'>Rails 3 upgrade part 3: Code fixes, views, and forms</a> <small>This is part 3 of my Rails 2 to Rails 3 upgrade experience. Part 1 is about the initial code upgrade and getting the application to boot while part 2...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>In the previous post, I outlined the steps I took to<a href="http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/"> upgrade and boot a Rails 3 application</a>. This time, I share my experience upgrading the routes file. By the way, I forgot to mention in the last post that I&#8217;m using <a href="http://www.railsupgradehandbook.com/">Rails 3 Upgrade Handbook by Jeremy McAnally</a>.</p>
<p>The task rails:upgrade:routes (comes with the rails_upgrade plugin) converts your Rails 2 routes into Rails 3 format. It handles most cases but you may still need to edit the generated routes depending on your setup.</p>
<p><strong>map.root</strong></p>
<p>Below, I show the old route and the generated version. </p>
<pre class="brush: ruby;">
# Rails 2
map.root :controller =&gt; 'search'

# Rails 3
match '/' =&gt; 'search#index'
</pre>
<p>The conversion is correct but since I use the named route &#8216;root_path&#8217; in my application, I had to change it:</p>
<pre class="brush: ruby;">
root :to =&gt; 'search#index'
</pre>
<p><strong>:as, :member, :any, :path_names</strong></p>
<pre class="brush: ruby;">
# Rails 2
map.resources :workspaces, :as =&gt; 'b', :member =&gt; { :widget =&gt; :get } do |workspace|
  # ...
end

# Rails 3
resources :workspaces do
  # ...
end
</pre>
<p>In Rail 3, :as  is for overriding the normal naming for named routes witout affecting the path. For example, the code below will recognize the path &#8216;/workspaces&#8217; and the named route becomes offices_path.</p>
<pre class="brush: ruby;">
resources :workspaces, :as =&gt; &quot;offices&quot;
</pre>
<p>In Rails 2, :as affects the path. In my example, &#8216;/b&#8217; routes the request to WorkspacesController. So for Rails 3 to recognize the path &#8216;/b&#8217;, I need to add another route.</p>
<pre class="brush: ruby;">
match 'b' =&gt; 'workspaces#index'
</pre>
<p>The rails:upgrade:routes did not convert the following member route and had to be added.</p>
<pre class="brush: ruby;">
:member =&gt; { :widget =&gt; :get }
</pre>
<p>The new route becomes:</p>
<pre class="brush: ruby;">
resources :workspaces do
  get :widget, :on =&gt; :member
end
</pre>
<p>In Rails 2, you can use the :any option to define a custom route that responds to any request method. </p>
<pre class="brush: ruby;">
# Rails 2
workspace.resource :twitter_account, :member =&gt; { :authorize =&gt; :any }, :path_names =&gt; { :edit =&gt; 'request_authorization' }

# generated by rails:upgrade:routes
resource :twitter_account do
  member do
    any :authorize
  end
end
</pre>
<p>The rails:upgrade:routes converted the :any option. However,  when I booted the application, it raised an exception:</p>
<pre class="brush: ruby;">
undefined method `any' for #&lt;ActionDispatch::Routing::Mapper:0xb71b6fcc&gt; (NoMethodError)
</pre>
<p>To fix this, I replaced the offending line with a match method.</p>
<pre class="brush: ruby;">
resource :twitter_account do
  match :authorize, :on =&gt; :member
end
</pre>
<p>:path_names was also not included in the generated route so has to be added as well.</p>
<pre class="brush: ruby;">
resource :twitter_account, :path_names =&gt; { :edit =&gt; 'request_authorization' } do
  match :authorize, :on =&gt; :member
end
</pre>
<p><strong>Specifying a different controller</strong></p>
<pre class="brush: ruby;">
# Rails 2
map.resource :settings, :controller =&gt; 'users' do |settings|
  settings.resource :twitter_account, :name_prefix =&gt; nil, :member =&gt; { :authorize =&gt; :any }, :path_names =&gt; { :edit =&gt; 'request_authorization' }
end

# generated by rake:upgrade:routes
resource :settings do
  resource :twitter_account do
    member do
      any :authorize
    end
  end
end
</pre>
<p>To fix, just specify the controller</p>
<pre class="brush: ruby;">
resource :settings,:controller =&gt; :users do
  # ...
end
</pre>
<p><strong>Undefined named route helper</strong></p>
<p>I encountered this exception while trying the application:</p>
<pre class="brush: ruby;">
undefined method `edit_twitter_account_path'
</pre>
<p>In Rails 2, this is the route that created this named route:</p>
<pre class="brush: ruby;">
map.resource :settings, :controller =&gt; 'users' do |settings|
  settings.resource :twitter_account, :name_prefix =&gt; nil, :member =&gt; { :authorize =&gt; :any }, :path_names =&gt; { :edit =&gt; 'request_authorization' }
end
</pre>
<p>This is a bit tricky for me because I can&#8217;t remember why I nested it :) Nevertheless, to fix the Rails 3 error, I moved :twitter_account outside of :settings. The correct Rails routes now look like these:</p>
<pre class="brush: ruby;">
resource :settings, :controller =&gt; :users
resource :twitter_account, :path_names =&gt; { :edit =&gt; 'request_authorization' } do
  match :authorize, :on =&gt; :member
end
</pre>
<p><strong>Custom polymorphic named route helper</strong></p>
<p>A long time ago, I played around with polymorphic paths. In hindsight, that is a waste of time but back then it was fun or should I say a time well wasted. I have a named route helper that takes any object and used like this:</p>
<pre class="brush: ruby;">
# in views
link_to 'invitations', invitations_path(@voteable)

# definition
module RoutesHelper
  def invitations_path(voteable)
    send(&quot;#{voteable.class.name.underscore}_invitations_path&quot;, voteable)
  end

  def workspace_invitations_path(workspace)
    super(:workspace_id =&gt; workspace)
  end

  # ...
end
</pre>
<p>In Rails 3, my named route helper is not being called. Thus, wrong URL is generated. I know, I know it should have been a simple <a href="http://api.rubyonrails.org/classes/ActionController/PolymorphicRoutes.html">polymorphic_path</a> call but I still wonder why my method is not called. Moving on, the new ruby is:</p>
<pre class="brush: ruby;">
link_to 'invitations', polymorphic_path([@voteable, :invitations])
</pre>
<p>I cheated a bit here because I want this post to focus on routes. Along the way, I had to update non-route related code to discover the route problems. <a href="http://edgeguides.rubyonrails.org/routing.html">You can learn more about Rails 3 routes from this RailsGuides page</a>.</p>
<p>There are still more updates to be done and I&#8217;ll share them in other posts. Just like your favorite late night infomercial, &#8220;Wait! There&#8217;s more&#8221;.</p>
<p>Next: <a href="http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/">Rails 3 upgrade part 3: Code fixes, views, and forms</a></p>
<p>Previous:  <a href="http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/">Rails 3 upgrade Part 1: Booting the application</a></p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 4: Prototype helpers and Javascript'>Rails 3 upgrade part 4: Prototype helpers and Javascript</a> <small>Rails 3 is embracing the unobtrusive Javascript (or UJS) mantra which is good because it is the right way; at the same time, it is bad because many applications will...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 1: Booting the application'>Rails 3 upgrade part 1: Booting the application</a> <small>It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 3: Code fixes, views, and forms'>Rails 3 upgrade part 3: Code fixes, views, and forms</a> <small>This is part 3 of my Rails 2 to Rails 3 upgrade experience. Part 1 is about the initial code upgrade and getting the application to boot while part 2...</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/gWialKSTK7iFQvxm7BQiw9jP0Jg/0/da"><img src="http://feedads.g.doubleclick.net/~a/gWialKSTK7iFQvxm7BQiw9jP0Jg/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/gWialKSTK7iFQvxm7BQiw9jP0Jg/1/da"><img src="http://feedads.g.doubleclick.net/~a/gWialKSTK7iFQvxm7BQiw9jP0Jg/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/rails-3-upgrade-part-2-routes/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Rails 3 upgrade part 1: Booting the application</title>
		<link>http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/</link>
		<comments>http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 07:53:47 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Geekiness]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=752</guid>
		<description><![CDATA[It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live and breath on the edge, upgrades are one of these things we try to avoid as much as possible. Still, there is always a sense [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-2-routes/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 2: Routes'>Rails 3 upgrade part 2: Routes</a> <small>In the previous post, I outlined the steps I took to upgrade and boot a Rails 3 application. This time, I share my experience upgrading the routes file. By the...</small></li>
<li><a href='http://gregmoreno.ca/deploy-a-rails-3-sqlite3-application-in-tomcat-using-jruby/' rel='bookmark' title='Permanent Link: Deploy a Rails 3, Sqlite3 application in Tomcat using JRuby'>Deploy a Rails 3, Sqlite3 application in Tomcat using JRuby</a> <small>and have a Ruby version running side-by-side. A few months ago I got interested in JRuby while researching for text mining algorithms. I found some gems but they are either...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 4: Prototype helpers and Javascript'>Rails 3 upgrade part 4: Prototype helpers and Javascript</a> <small>Rails 3 is embracing the unobtrusive Javascript (or UJS) mantra which is good because it is the right way; at the same time, it is bad because many applications will...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live and breath on the edge, upgrades are one of these things we try to avoid as much as possible.  Still, there is always a sense of excitement in trying something new even if it adds problems to an already stable piece of code.</p>
<p>For a little background, I am upgrading a Rails app several of friends and I have written last year. The code is available at <a href="http://github.com/gregmoreno/propsify">github</a>.</p>
<p>In this post, I share the steps I did to boot the application. This doesn&#8217;t mean the upgrade went fine neither the app is ready to go. It only means all the required initialization are OK. In succeeding posts, I share my experiences in upgrading the app to a green state.</p>
<p>First, my environment.</p>
<pre class="brush: bash;">
greg@piccolo:~/dev/projects/propsify3$ rvm info
ruby-1.8.7-p299@propsify:

  system:
    uname:        &quot;Linux piccolo 2.6.31-22-generic #61-Ubuntu SMP Wed Jul 28 01:57:06 UTC 2010 i686 GNU/Linux&quot;
    shell:        &quot;bash&quot;
    version:      &quot;4.0.33(1)-release&quot;

  rvm:
    version:      &quot;rvm 0.1.44 by Wayne E. Seguin (wayneeseguin@gmail.com) [http://rvm.beginrescueend.com/]&quot;

  ruby:
    interpreter:  &quot;ruby&quot;
    version:      &quot;1.8.7&quot;
    date:         &quot;2010-06-23&quot;
    platform:     &quot;i686-linux&quot;
    patchlevel:   &quot;2010-06-23 patchlevel 299&quot;
    full_version: &quot;ruby 1.8.7 (2010-06-23 patchlevel 299) [i686-linux]&quot;

greg@piccolo:~/dev/projects/propsify3$ script/about
About your application's environment
Ruby version              1.8.7 (i686-linux)
RubyGems version          1.3.7
Rack version              1.0 bundled
Rails version             2.3.2
Active Record version     2.3.2
Action Pack version       2.3.2
Active Resource version   2.3.2
Action Mailer version     2.3.2
Active Support version    2.3.2
Application root          /mnt/hgfs/greg-mini/dev/projects/propsify
Environment               development
Database adapter          postgresql
Database schema version   20100113032723

greg@piccolo:~/dev/projects/propsify3$ gem list

*** LOCAL GEMS ***

actionmailer (2.3.2)
actionpack (2.3.2)
activerecord (2.3.2)
activeresource (2.3.2)
activesupport (2.3.2)
geokit (1.5.0)
json (1.4.5)
mime-types (1.16)
oauth (0.4.1)
pg (0.9.0)
rails (2.3.2)
rake (0.8.7)
RedCloth (4.2.2)
twitter_oauth (0.3.2)

greg@piccolo:~/dev/projects/propsify3$ ls vendor/gems/
authlogic-2.1.3  geokit-1.5.0  haml-2.2.16  macaddr-1.0.0  twitter_oauth-0.3.2  uuid-2.1.0

greg@piccolo:~/dev/projects/propsify3$ ls vendor/plugins/
acts_as_commentable        geokit-rails     is_taggable   thinking-sphinx      will_paginate
declarative_authorization  gravatar-plugin  jrails        validates_date_time
exception_notification     haml             subdomain-fu  vote_fu
</pre>
<p><strong>Step 1: Install rails 3</strong></p>
<pre class="brush: plain;">
gem install rails --pre
</pre>
<p><strong>Step 2: Install the plugin tool </strong></p>
<pre class="brush: plain;">
script/plugin install git://github.com/rails/rails_upgrade.git
</pre>
<p><strong>Step 3: Show upgrade checklist</strong></p>
<pre class="brush: ruby;">
rake rails:upgrade:check
</pre>
<p>This task lists the items you should watch out for when doing the upgrade. You don&#8217;t need to fix everything right away (some are deprecation notice) but review the checklist nevertheless.</p>
<p><strong>Step 4: Generate the new routes</strong></p>
<pre class="brush: plain;">
rake rails:upgrade:routes
</pre>
<p>This task reads the current config/routes.rb and outputs a Rails 3 version.<br />
Don&#8217;t worry, it doesn&#8217;t override your routes file. Keep this in a safe place for later use.</p>
<p><strong>IMPORTANT:</strong> I actually didn&#8217;t realize I did the right thing until after the actual code upgrade. When I tried generating the new routes after the code change, it outputted an empty block. I have no idea if this is unique to my case but just to be sure, generate the routes beforehand and keep a copy.</p>
<p><strong>Step 5: Create Gemfiles</strong></p>
<pre class="brush: plain;">
rails:upgrade:gems
</pre>
<p>Next is to generate the file &#8216;Gemfile&#8217;. In Rails 2, the gems you need are listed in config/environment.rb while in Rails 3 the gems are listed in the Gemfile. Gemfile is used by the program &#8216;bundler&#8217; to manage the gems required by your application. Unfortunately, this task didn&#8217;t include the gems I listed in environment.rb so I have to add it later.</p>
<p><strong>Step 6: Backup your files</strong></p>
<pre class="brush: plain;">
rails:upgrade:backup
</pre>
<p>I hope you are working on another branch (or a copy) but just in case you are not, run this task to make copies of the files that will be affected during the upgrade.</p>
<p>Now comes the juicy part. </p>
<p><strong>Step 7: Generate the Rails 3 app on top of your Rails 2 app</strong></p>
<pre class="brush: plain;">
rails new propsify3 -d postgresql
</pre>
<p>Run this command in your app&#8217;s parent folder. In my case, my app&#8217;s name and pathname is &#8216;propsify3&#8242; and I am using postgresql as my database. This command created and replaced a bunch of files. Since you&#8217;ve backed-up everything, there&#8217;s nothing to worry. </p>
<p><strong>Step 8: Move code from environment.rb to application.rb</strong></p>
<p>Your new config/environment.rb file looks like it went through a rigorous diet. You can leave this file for now. What is important now is you move the initializer code from your config/environment.rb.rails2 to config/application.rb.  These are the config.* lines except the config.gem which goes to Gemfile.</p>
<p><strong>Step 9: Convert the new routes</strong></p>
<p>You can still use the existing routes until 3.1 but since there&#8217;s a tool to help you migrate, I suggest doing it. At this point, when I tried the rails:upgrade:routes, no routes were generated. So make sure you generate the routes before Step 7.</p>
<p><strong>Step 10: Delete new_rails_defaults.rb </strong></p>
<pre class="brush: plain;">
rm config/initializers/new_rails_defaults
</pre>
<p><strong>Step 11: Upgrade the plugins and gems</strong></p>
<p>Many plugins are now available as gems. Check your plugins and gems at <a href="http://railsplugins.org">http://railsplugins.org</a>. In my case, the following plugins were converted to gems:</p>
<pre class="brush: ruby;">
acts_as_commentable
declarative_authorization
haml
will_paginate
thinking-sphinx
</pre>
<p>Unfortunately, the plugins below are not yet ready for Rails 3. I removed them for now and all code that references them.</p>
<pre class="brush: ruby;">
jrails
subdomain-fu
vote_fu
</pre>
<p><strong>IMPORTANT</strong>: In your Gemfile, make sure you check specify the right version that is compatible with Rails 3. Some gems are still in the pre-release version and will  not be downloaded if you don&#8217;t specify a version in your Gemfile. For example, this is a snippet from my Gemfile:</p>
<pre class="brush: ruby;">
gem 'pg'
gem 'acts_as_commentable'
gem 'declarative_authorization'
gem 'haml'
gem 'thinking-sphinx', '2.0.0.rc1', :require =&gt; 'thinking_sphinx'
gem 'will_paginate', '3.0.pre2'
gem 'uuid'
gem 'geokit'
</pre>
<p><strong>Step 12: Update initialization code</strong></p>
<p>After step 10 you are good to go, if you&#8217;re lucky. In my case, I had to remove some patches and change code to boot the application.</p>
<pre class="brush: ruby;">
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(date_time_formats)
</pre>
<p>This fails in Rails 3 because core extensions have been moved out of their modules and are now included in classes they extend. For example, to fix the date format problem do:</p>
<pre class="brush: ruby;">
Date::DATE_FORMATS.merge!(date_time_formats)
</pre>
<p><strong>Step 13: Boot the app</strong></p>
<pre class="brush: plain;">
rails server
</pre>
<p>Yay! If you are wondering what happened to <code>script/server</code> command,  Rails went the &#8220;Merb way&#8221; and consolidated the <code>script/*</code> commands into  the <code>rails</code> script.</p>
<p>By now, you should see the famous Rails&#8217; &#8220;Welcome aboard&#8221; message in your browser. </p>
<p><strong>Step 14: Remove public/index.html</strong></p>
<p>Now, you can try if your application is working.</p>
<p>There are still more work to do like moving to the ActiveRecord/ActiveRelation API and removing the deprecation notices. Before moving on, I still need to fix the problems in my routes and unsupported gems which I will tackle in my next post.</p>
<p><strong>Next</strong>: <a href="http://gregmoreno.ca/rails-3-upgrade-part-2-routes/">Rails 3 upgrade Part 2: Routes</a></p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-2-routes/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 2: Routes'>Rails 3 upgrade part 2: Routes</a> <small>In the previous post, I outlined the steps I took to upgrade and boot a Rails 3 application. This time, I share my experience upgrading the routes file. By the...</small></li>
<li><a href='http://gregmoreno.ca/deploy-a-rails-3-sqlite3-application-in-tomcat-using-jruby/' rel='bookmark' title='Permanent Link: Deploy a Rails 3, Sqlite3 application in Tomcat using JRuby'>Deploy a Rails 3, Sqlite3 application in Tomcat using JRuby</a> <small>and have a Ruby version running side-by-side. A few months ago I got interested in JRuby while researching for text mining algorithms. I found some gems but they are either...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-4-prototype-helpers-and-javascript/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 4: Prototype helpers and Javascript'>Rails 3 upgrade part 4: Prototype helpers and Javascript</a> <small>Rails 3 is embracing the unobtrusive Javascript (or UJS) mantra which is good because it is the right way; at the same time, it is bad because many applications will...</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/5ah40Bbd_Jymumx_nbozawPSUJw/0/da"><img src="http://feedads.g.doubleclick.net/~a/5ah40Bbd_Jymumx_nbozawPSUJw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/5ah40Bbd_Jymumx_nbozawPSUJw/1/da"><img src="http://feedads.g.doubleclick.net/~a/5ah40Bbd_Jymumx_nbozawPSUJw/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Coding gems 31-40</title>
		<link>http://gregmoreno.ca/coding-gems-31-40/</link>
		<comments>http://gregmoreno.ca/coding-gems-31-40/#comments</comments>
		<pubDate>Thu, 24 Jun 2010 04:48:18 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Geekiness]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=746</guid>
		<description><![CDATA[#31 All non-trivial abstractions, to some degree, are leaky. Joel Spolsky #32 Five different programmers can solve the same problem five different ways #33 Don&#8217;t write 200 lines of code when 10 will do #34 If the &#8220;box&#8221; is the boundary of constraints and conditions, don&#8217;t think outside the box—find the tbox. Andy Hunt, Dave [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/coding-gems-1-10/' rel='bookmark' title='Permanent Link: Coding gems 1-10'>Coding gems 1-10</a> <small>#1 The more dogmatic you are about applying a design method, the fewer real-life problems you are going to solve &#8211; P.J. Plauger #2 Let Ruby be Ruby. Let Java...</small></li>
<li><a href='http://gregmoreno.ca/coding-gems-21-30/' rel='bookmark' title='Permanent Link: Coding gems 21-30'>Coding gems 21-30</a> <small>#21 A well-written code is a joy to write and a joy to read. #22 If you can&#8217;t explain something to a six-year-old, you really don&#8217;t understand it yourself. Albert...</small></li>
<li><a href='http://gregmoreno.ca/coding-gems-11-20/' rel='bookmark' title='Permanent Link: Coding gems 11-20'>Coding gems 11-20</a> <small>#11 Either you code it so simple there are obviously no deficiencies or so complicated that there are no obvious deficiencies #12 In a room full of expert software designers,...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>#31 All non-trivial abstractions, to some degree, are leaky. Joel Spolsky</p>
<p>#32 Five different programmers can solve the same problem five different ways</p>
<p>#33 Don&#8217;t write 200 lines of code when 10 will do</p>
<p>#34 If the &#8220;box&#8221; is the boundary of constraints and conditions, don&#8217;t think outside the box—find the tbox. Andy Hunt, Dave Thomas</p>
<p>#35 Complexity and communication costs rise with the square of the number of developers, while work done rises linearly. Fred Brooks</p>
<p>#36 Tests only prove the presence of errors &#8211; not the absence of them</p>
<p>#37 A metaprogrammer is someone who writes code that writes code  for food</p>
<p>#38 The task on a project is not to try for complete communication but to manage the incompleteness of our communications.  Cockburn</p>
<p>#39  A good plan violently executed now is better than a perfect plan next week. Patton</p>
<p>#40 Tests first, then code&#8230;. or the kitten gets it</p>
<p><a href="http://ruby.sadi.st/Kittens.html"><img class="alignnone" title="Kitten" src="http://ruby.sadi.st/Kittens_files/Kitten+Gun.jpg" alt="" width="600" height="450" /></a></p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/coding-gems-1-10/' rel='bookmark' title='Permanent Link: Coding gems 1-10'>Coding gems 1-10</a> <small>#1 The more dogmatic you are about applying a design method, the fewer real-life problems you are going to solve &#8211; P.J. Plauger #2 Let Ruby be Ruby. Let Java...</small></li>
<li><a href='http://gregmoreno.ca/coding-gems-21-30/' rel='bookmark' title='Permanent Link: Coding gems 21-30'>Coding gems 21-30</a> <small>#21 A well-written code is a joy to write and a joy to read. #22 If you can&#8217;t explain something to a six-year-old, you really don&#8217;t understand it yourself. Albert...</small></li>
<li><a href='http://gregmoreno.ca/coding-gems-11-20/' rel='bookmark' title='Permanent Link: Coding gems 11-20'>Coding gems 11-20</a> <small>#11 Either you code it so simple there are obviously no deficiencies or so complicated that there are no obvious deficiencies #12 In a room full of expert software designers,...</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/UNnjZIsANOZoufAWCLTRJJ7V5bg/0/da"><img src="http://feedads.g.doubleclick.net/~a/UNnjZIsANOZoufAWCLTRJJ7V5bg/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/UNnjZIsANOZoufAWCLTRJJ7V5bg/1/da"><img src="http://feedads.g.doubleclick.net/~a/UNnjZIsANOZoufAWCLTRJJ7V5bg/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/coding-gems-31-40/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DHH’s RailsConf 2010 Keynote Video</title>
		<link>http://gregmoreno.ca/dhh%e2%80%99s-railsconf-2010-keynote-video/</link>
		<comments>http://gregmoreno.ca/dhh%e2%80%99s-railsconf-2010-keynote-video/#comments</comments>
		<pubDate>Fri, 11 Jun 2010 22:59:59 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Sideways]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=743</guid>
		<description><![CDATA[The keynote is about Rails 3.0 and the many enhancements it bring to make web application development more fun. The improvements in writing database queries (via ActiveRelation), routes, ActionMailer are really neat and I believe would make it easier for developers to get on board with Rails. The official release will be available in a [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 1: Booting the application'>Rails 3 upgrade part 1: Booting the application</a> <small>It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-2-routes/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 2: Routes'>Rails 3 upgrade part 2: Routes</a> <small>In the previous post, I outlined the steps I took to upgrade and boot a Rails 3 application. This time, I share my experience upgrading the routes file. By the...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 3: Code fixes, views, and forms'>Rails 3 upgrade part 3: Code fixes, views, and forms</a> <small>This is part 3 of my Rails 2 to Rails 3 upgrade experience. Part 1 is about the initial code upgrade and getting the application to boot while part 2...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/b0iKYRKtAsA&#038;color1=0xb1b1b1&#038;color2=0xd0d0d0&#038;hl=en_US&#038;feature=player_embedded&#038;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><embed src="http://www.youtube.com/v/b0iKYRKtAsA&#038;color1=0xb1b1b1&#038;color2=0xd0d0d0&#038;hl=en_US&#038;feature=player_embedded&#038;fs=1" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="385"></embed></object></p>
<p>The keynote is about Rails 3.0 and the many enhancements it bring to make web application development more fun.  The improvements in writing database queries (via <a href="http://rubyonrails.org/screencasts/rails3/active-relation-active-model">ActiveRelation</a>), routes, ActionMailer are really neat and I believe would make it easier for  developers to get on board with Rails.</p>
<p>The official release will be available in a few weeks but the current version is already good enough for production use according to DHH.</p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 1: Booting the application'>Rails 3 upgrade part 1: Booting the application</a> <small>It&#8217;s time for another Rails upgrade! We all have our share of bad experiences and frustrations every time we upgrade a piece of software. Even for technical people who live...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-2-routes/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 2: Routes'>Rails 3 upgrade part 2: Routes</a> <small>In the previous post, I outlined the steps I took to upgrade and boot a Rails 3 application. This time, I share my experience upgrading the routes file. By the...</small></li>
<li><a href='http://gregmoreno.ca/rails-3-upgrade-part-3-code-fixes-views-and-forms/' rel='bookmark' title='Permanent Link: Rails 3 upgrade part 3: Code fixes, views, and forms'>Rails 3 upgrade part 3: Code fixes, views, and forms</a> <small>This is part 3 of my Rails 2 to Rails 3 upgrade experience. Part 1 is about the initial code upgrade and getting the application to boot while part 2...</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/qM-9FIlVKBSWPAVmpdjJ7ok_IXw/0/da"><img src="http://feedads.g.doubleclick.net/~a/qM-9FIlVKBSWPAVmpdjJ7ok_IXw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/qM-9FIlVKBSWPAVmpdjJ7ok_IXw/1/da"><img src="http://feedads.g.doubleclick.net/~a/qM-9FIlVKBSWPAVmpdjJ7ok_IXw/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/dhh%e2%80%99s-railsconf-2010-keynote-video/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby 101: Make your class behave like a Ruby built-in</title>
		<link>http://gregmoreno.ca/ruby-101-make-your-class-behave-like-a-ruby-built-in/</link>
		<comments>http://gregmoreno.ca/ruby-101-make-your-class-behave-like-a-ruby-built-in/#comments</comments>
		<pubDate>Thu, 10 Jun 2010 02:10:36 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Geekiness]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=735</guid>
		<description><![CDATA[I got re-acquianted with this scenario while working on the OpenAmplify gem &#8211; a wrapper for the OpenAmplify API. When you give the api a text like a blog comment, it will return a list of common terms, opinion scores, named locations, and other information that can be used for text mining operations. The OpenAmplify [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/ruby-101-how-to-add-methods-to-a-ruby-class/' rel='bookmark' title='Permanent Link: Ruby 101: How to add methods to a Ruby class'>Ruby 101: How to add methods to a Ruby class</a> <small>Let’s add a method that checks whether an Array has many elements. a = [1,2,3] a.many? # NoMethodError: undefined method `many?' Let’s fix this by adding a new method to...</small></li>
<li><a href='http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/' rel='bookmark' title='Permanent Link: How to create a class on the fly in Ruby'>How to create a class on the fly in Ruby</a> <small>&#8220;So what if Ruby is dynamic?&#8221; This is often the reaction I get whenever I tell friends that Ruby allows you to fiddle with your program at runtime; followed by...</small></li>
<li><a href='http://gregmoreno.ca/ruby-101-hash-initialization-gotcha/' rel='bookmark' title='Permanent Link: Ruby 101: Hash initialization gotcha'>Ruby 101: Hash initialization gotcha</a> <small>I have a code that counts how many times a word occurs &#8211; a perfect fit for Hash. def word_counts(words) counts = Hash.new(0) words.each do |word| counts[word] += 1 end...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I got re-acquianted with this scenario while working on the<a href="http://github.com/gregmoreno/openamplify"> OpenAmplify gem</a> &#8211; a wrapper for the <a href="http://community.openamplify.com/blogs/quickstart/pages/overview.aspx">OpenAmplify API</a>.  When you give the api a text like a blog comment, it will return a list of common terms, opinion scores, named locations, and other information that can be used for text mining operations. </p>
<p>The OpenAmplify returns key-value pairs in an XML string by default, but it can also be in JSON, CSV, or RDF format. From a Ruby client’s point of view, we want it in Hash.  You can choose to use an XML library like Nokogiri but in my opinion, working with a Hash  fits nicely with Ruby.</p>
<p>Anyway, back to the problem.  I have an instance variable that holds the data.  One approach is to give clients access to the instance variable.</p>
<pre class="brush: ruby;">
class Response
  attr_reader :data

  def initialize
    @data = {}
  end
end

data = response.data
topics = data[‘Topics’]
</pre>
<p>One major issue with this approach is you’re exposing the internals of your class. What if you decided to rename the variable into ‘@results_in_hash_form’?  Then,  all programs that uses your code will break.  Worse,  you will be limited from enhancing the behavior of your class like lazy loading of the data.  You can wrap the access to your data inside a method but that still presents the problem of exposing the internals of your class. Also, that’s an unnecessary extra line of code :)</p>
<p>My suggestion is to make ‘Response’ behave like a Hash so we can do these:</p>
<pre class="brush: ruby;">
topics = response[‘Topics’]
response.has_key?(‘Topics’)

# And still have our own methods:
response.some_method_we_defined
</pre>
<p>So, how can we do this? The trick is to delegate the calls to the instance variable. One approach is to define the Hash methods you want to support:</p>
<pre class="brush: ruby;">
class Response

  [‘[]’, ‘has_key?’, ‘fetch’, ‘empty?’, ‘keys’].each do |method_name|
    class_eval &lt;&lt;-EOS
      def #{method}(*args)
         @data.send(‘#{method_name}’, *args)
      end
    EOS
  end

end
</pre>
<p>The code above is a shortcut to writing every method by hand. If you want to support all Hash methods, that would be a lot of typing.  </p>
<p>A better approach is to just take advantage of Ruby’s ‘method_missing’ which is called every time an undefined method is called.</p>
<pre class="brush: ruby;">
class Response

  def method_missing(name, *args, &amp;amp;block)
    @data.send(name, *args, &amp;amp;block)
  end

end
</pre>
<p>Of course, how your &#8216;method_missing&#8217; will look like depends on your requirements. In our simple case, we can simply delegate to @data.</p>
<p>This approach is called a &#8220;Dynamic Proxy&#8221; from the book <a href="http://pragprog.com/titles/ppmetr/metaprogramming-ruby">Metaprogramming Ruby by Paolo Perrota</a>. If you want to take your Ruby skills to the next level, I highly recommend this book.</p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/ruby-101-how-to-add-methods-to-a-ruby-class/' rel='bookmark' title='Permanent Link: Ruby 101: How to add methods to a Ruby class'>Ruby 101: How to add methods to a Ruby class</a> <small>Let’s add a method that checks whether an Array has many elements. a = [1,2,3] a.many? # NoMethodError: undefined method `many?' Let’s fix this by adding a new method to...</small></li>
<li><a href='http://gregmoreno.ca/how-to-create-a-class-on-the-fly-in-ruby/' rel='bookmark' title='Permanent Link: How to create a class on the fly in Ruby'>How to create a class on the fly in Ruby</a> <small>&#8220;So what if Ruby is dynamic?&#8221; This is often the reaction I get whenever I tell friends that Ruby allows you to fiddle with your program at runtime; followed by...</small></li>
<li><a href='http://gregmoreno.ca/ruby-101-hash-initialization-gotcha/' rel='bookmark' title='Permanent Link: Ruby 101: Hash initialization gotcha'>Ruby 101: Hash initialization gotcha</a> <small>I have a code that counts how many times a word occurs &#8211; a perfect fit for Hash. def word_counts(words) counts = Hash.new(0) words.each do |word| counts[word] += 1 end...</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/46NwTfP2ROF7wfEq0DVe5y-7gsY/0/da"><img src="http://feedads.g.doubleclick.net/~a/46NwTfP2ROF7wfEq0DVe5y-7gsY/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/46NwTfP2ROF7wfEq0DVe5y-7gsY/1/da"><img src="http://feedads.g.doubleclick.net/~a/46NwTfP2ROF7wfEq0DVe5y-7gsY/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/ruby-101-make-your-class-behave-like-a-ruby-built-in/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby 101: Hash initialization gotcha</title>
		<link>http://gregmoreno.ca/ruby-101-hash-initialization-gotcha/</link>
		<comments>http://gregmoreno.ca/ruby-101-hash-initialization-gotcha/#comments</comments>
		<pubDate>Wed, 12 May 2010 00:32:32 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Geekiness]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=732</guid>
		<description><![CDATA[I have a code that counts how many times a word occurs &#8211; a perfect fit for Hash. def word_counts(words) counts = Hash.new(0) words.each do &#124;word&#124; counts[word] += 1 end end categories = { :a =&#62; word_counts(‘some text’) :b =&#62; word_counts(‘another set of text’) } Somewhere, I use the hash returned by the word_counts method [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/ruby-101-make-your-class-behave-like-a-ruby-built-in/' rel='bookmark' title='Permanent Link: Ruby 101: Make your class behave like a Ruby built-in'>Ruby 101: Make your class behave like a Ruby built-in</a> <small>I got re-acquianted with this scenario while working on the OpenAmplify gem &#8211; a wrapper for the OpenAmplify API. When you give the api a text like a blog comment,...</small></li>
<li><a href='http://gregmoreno.ca/ruby-101-how-to-add-methods-to-a-ruby-class/' rel='bookmark' title='Permanent Link: Ruby 101: How to add methods to a Ruby class'>Ruby 101: How to add methods to a Ruby class</a> <small>Let’s add a method that checks whether an Array has many elements. a = [1,2,3] a.many? # NoMethodError: undefined method `many?' Let’s fix this by adding a new method to...</small></li>
<li><a href='http://gregmoreno.ca/ruby-101-how-to-filter-an-array-using-proc/' rel='bookmark' title='Permanent Link: Ruby 101: How to filter an Array using proc'>Ruby 101: How to filter an Array using proc</a> <small>Over at the PhRUG, a Ruby developer community based in the Philippines, we conduct code review sessions via our mailing list. A code is posted and members share alternative implementations....</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I have a code that counts how many times a word occurs &#8211; a perfect fit for Hash. </p>
<pre class="brush: plain;">
def word_counts(words)
  counts = Hash.new(0)
  words.each do |word|
    counts[word] += 1
  end
end

categories = {
  :a =&gt; word_counts(‘some text’)
  :b =&gt; word_counts(‘another set of text’)
}
</pre>
<p>Somewhere, I use the hash returned by the word_counts method to do some calculation.</p>
<pre class="brush: plain;">
def score(word_scores, words)
  words.each do |word|
    v = word_scores[word]
    v = 0.1 if v.nil?

    score += Math.log( v / some_value )
  end
end

categories.each do |category, word_counts|
  score(word_counts, %w{some random text})
end
</pre>
<p>When I run the score, I always get an ‘Infinity’.  After some debugging, the problem is this piece of code:</p>
<pre class="brush: plain;">
v = word_scores[word]
v = 0.1 if v.nil?
</pre>
<p>‘word_scores’  returns 0 if  ‘word’ doesn’t exist; not nil which is the default behavior. Later, I realized I initialized it via   Hash.new(0) which makes 0 the default value.  In fact, it is not even necessary to check for nil or 0. All we want is to retrieve the value referenced by the key, and if the key does not exist, give me 0.1.</p>
<pre class="brush: plain;">
v = word_counts.fetch word, 0.1
</pre>
<p>By the way, the code is from a simple exercise on <a href="http://www.rubyoncloud.org/questions/how-to-classify-text-as-spam-or-funny-or-what-have-you-using-naive-bayes-algorithm">Naive Bayes algorithm to classify text</a>.</p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/ruby-101-make-your-class-behave-like-a-ruby-built-in/' rel='bookmark' title='Permanent Link: Ruby 101: Make your class behave like a Ruby built-in'>Ruby 101: Make your class behave like a Ruby built-in</a> <small>I got re-acquianted with this scenario while working on the OpenAmplify gem &#8211; a wrapper for the OpenAmplify API. When you give the api a text like a blog comment,...</small></li>
<li><a href='http://gregmoreno.ca/ruby-101-how-to-add-methods-to-a-ruby-class/' rel='bookmark' title='Permanent Link: Ruby 101: How to add methods to a Ruby class'>Ruby 101: How to add methods to a Ruby class</a> <small>Let’s add a method that checks whether an Array has many elements. a = [1,2,3] a.many? # NoMethodError: undefined method `many?' Let’s fix this by adding a new method to...</small></li>
<li><a href='http://gregmoreno.ca/ruby-101-how-to-filter-an-array-using-proc/' rel='bookmark' title='Permanent Link: Ruby 101: How to filter an Array using proc'>Ruby 101: How to filter an Array using proc</a> <small>Over at the PhRUG, a Ruby developer community based in the Philippines, we conduct code review sessions via our mailing list. A code is posted and members share alternative implementations....</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/r1-FCUUzCX-n33j7qqtjLKqL4So/0/da"><img src="http://feedads.g.doubleclick.net/~a/r1-FCUUzCX-n33j7qqtjLKqL4So/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/r1-FCUUzCX-n33j7qqtjLKqL4So/1/da"><img src="http://feedads.g.doubleclick.net/~a/r1-FCUUzCX-n33j7qqtjLKqL4So/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/ruby-101-hash-initialization-gotcha/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Starting a Q&amp;A website: Canada Work Visa</title>
		<link>http://gregmoreno.ca/canada-work-visa-questions-answers/</link>
		<comments>http://gregmoreno.ca/canada-work-visa-questions-answers/#comments</comments>
		<pubDate>Fri, 30 Apr 2010 23:45:54 +0000</pubDate>
		<dc:creator>Greg Moreno</dc:creator>
				<category><![CDATA[Sideways]]></category>
		<category><![CDATA[canada]]></category>
		<category><![CDATA[visa]]></category>

		<guid isPermaLink="false">http://gregmoreno.ca/?p=725</guid>
		<description><![CDATA[Last week I created a Q&#38;A website for things related to Canada work visa. (This is actually a project of my wife&#8217;s cousins and I&#8217;m just helping them out sort out the technical details.) If you have questions about getting a work visa or issues with your Canadian work permit,  just post your questions and the [...]


Related posts:<ol><li><a href='http://gregmoreno.ca/10-best-cities-for-small-business-in-canada-and-us/' rel='bookmark' title='Permanent Link: 10 Best cities in Canada and US for small business'>10 Best cities in Canada and US for small business</a> <small>Canada: Big cities are bad for small business, according to recent findings. If you&#8217;re an entrepreneur, the best places in Canada to start and operate a successful company are found...</small></li>
<li><a href='http://gregmoreno.ca/top-20-innovative-companies-in-canada-2009/' rel='bookmark' title='Permanent Link: Top 20 Innovative Companies in Canada 2009'>Top 20 Innovative Companies in Canada 2009</a> <small>&#8230;from the Canadian Innovation Exchange: Aeryon Labs Inc. Builds military-like devices for imaging CognoVision Solutions Inc. Analytics for digital signage using face detection and tracking Darwin Dimensions Build your own...</small></li>
<li><a href='http://gregmoreno.ca/tax-tips-for-canadian-families/' rel='bookmark' title='Permanent Link: Tax tips for Canadian families'>Tax tips for Canadian families</a> <small>I was looking for a book for wife at Shoppers (Kingsway) when I saw 101 Tax Secrets For Canadians by Tim Cestnick. The tax D-day is fast approaching and being...</small></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Last week I created a Q&amp;A website for things related to <a href="http://canadaworkvisa.shapado.com/">Canada work visa</a>. (This is actually a project of my wife&#8217;s cousins and I&#8217;m just helping them out sort out the technical details.) If you have questions about getting a work visa or issues with your <a href="http://www.cic.gc.ca/english/work/apply-how.asp">Canadian work permit</a>,  just post your questions and the nice people over there will help you out. Here are some popular questions:</p>
<ul>
<li><a href="http://canadaworkvisa.shapado.com/questions/do-i-need-a-lawyer-to-get-a-work-visa-in-canada">Do I need a lawyer to get a work visa in Canada</a>?</li>
<li><a href="http://canadaworkvisa.shapado.com/questions/do-i-need-to-show-proof-of-funds-to-get-a-canada-work-visa">Do I need to show proof funds to get a Canada work visa</a>?</li>
</ul>
<p>Interesting because my wife and I came to Canada under a work visa two years ago but we neither needed both. Our situation might be different than yours, though.</p>
<p>The <a href="http://canadaworkvisa.shapado.com/">Canada Work Visa</a> site runs on <a href="http://shapado.com/">Shapado</a> &#8211; an open-source software based on the popular <a href="http://stackoverflow.com/about">StackOverflow</a> model.  It&#8217;s like a forum where members can post their questions and members can answer. The problem with forums is often the best answer is buried somewhere in the myriad of responses.  A member, especially a new one, would have to read every replies until he finds the best answer.   In Shapado, members can vote for the answer like in <a href="http://digg.com">Digg</a> and the answer that has the most votes will go to the top of the thread along with the number of votes. This approach makes it much easier to find the answer.</p>
<p><img class="alignnone" title="Canada work visa" src="http://img.skitch.com/20100430-p1bnq9gqy3qf2auajetsc9k8s5.jpg" alt="" width="736" height="233" /></p>
<p>Members  can only also vote down an answer. Take that spammers!  I think the ability to vote-down an answer is as important as voting-up to filter the noise from the signal.  One time, I was browsing a forum related to Canada immigration and there&#8217;s one member who posted that he&#8217;s working for the <a href="http://www.cic.gc.ca/english/index.asp">Canada Immigration Center</a> and asking members to share their email and  application details.  Later in  the discussions,  somebody warned that the Canadian government doesn&#8217;t ask for this kind of information. Unfortunately, some took the bait. In the Canada Work Visa website, this answer will be voted-down and would go all the way to the bottom. And with all the negative votes it had, every visitor is warned immediately.</p>
<p><img class="alignnone" title="Do I need a lawyer to a Canada work visa" src="http://img.skitch.com/20100430-t3wnf9cnig6dqp25kkqf5igxpb.jpg" alt="" width="510" height="575" /></p>
<p>If you know somebody with  <a href="http://canadaworkvisa.shapado.com">Canada work visa related question</a>, please share this website.</p>
<p>If you want to start a question and answer website, I highly recommend <a href="http://shapado.com">Shapado</a>.</p>


<p>Related posts:<ol><li><a href='http://gregmoreno.ca/10-best-cities-for-small-business-in-canada-and-us/' rel='bookmark' title='Permanent Link: 10 Best cities in Canada and US for small business'>10 Best cities in Canada and US for small business</a> <small>Canada: Big cities are bad for small business, according to recent findings. If you&#8217;re an entrepreneur, the best places in Canada to start and operate a successful company are found...</small></li>
<li><a href='http://gregmoreno.ca/top-20-innovative-companies-in-canada-2009/' rel='bookmark' title='Permanent Link: Top 20 Innovative Companies in Canada 2009'>Top 20 Innovative Companies in Canada 2009</a> <small>&#8230;from the Canadian Innovation Exchange: Aeryon Labs Inc. Builds military-like devices for imaging CognoVision Solutions Inc. Analytics for digital signage using face detection and tracking Darwin Dimensions Build your own...</small></li>
<li><a href='http://gregmoreno.ca/tax-tips-for-canadian-families/' rel='bookmark' title='Permanent Link: Tax tips for Canadian families'>Tax tips for Canadian families</a> <small>I was looking for a book for wife at Shoppers (Kingsway) when I saw 101 Tax Secrets For Canadians by Tim Cestnick. The tax D-day is fast approaching and being...</small></li>
</ol></p>
<p><a href="http://feedads.g.doubleclick.net/~a/Vl3NDEADVUNnNyrK0dKLKleCgis/0/da"><img src="http://feedads.g.doubleclick.net/~a/Vl3NDEADVUNnNyrK0dKLKleCgis/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Vl3NDEADVUNnNyrK0dKLKleCgis/1/da"><img src="http://feedads.g.doubleclick.net/~a/Vl3NDEADVUNnNyrK0dKLKleCgis/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://gregmoreno.ca/canada-work-visa-questions-answers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
