<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>Tommy Chheng &#187; Ruby</title>
	<atom:link href="http://tommy.chheng.com/index.php/category/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://tommy.chheng.com</link>
	<description>All Things Programming!</description>
	<lastBuildDate>Wed, 11 Aug 2010 05:58:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Setting up a Hudson Continuous Integration Testing Server for Ruby(and Rails)</title>
		<link>http://tommy.chheng.com/index.php/2010/08/setting-up-a-hudson-continuous-integration-testing-server-for-rubyand-rails/</link>
		<comments>http://tommy.chheng.com/index.php/2010/08/setting-up-a-hudson-continuous-integration-testing-server-for-rubyand-rails/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 05:55:41 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=337</guid>
		<description><![CDATA[If you work on a project with multiple developers, a continuous integration testing setup is a must. A CI package will run automated tests on a server on a set(daily) or evented(whenever commits are made) interval. There are a number of continuous integration packages for Ruby software including CI Joe, CruiseControl.rb. I chose Hudson because [...]]]></description>
			<content:encoded><![CDATA[<p>If you work on a project with multiple developers, a continuous integration testing setup is a must. A CI package will run automated tests on a server on a set(daily) or evented(whenever commits are made) interval.<br />
<img src="http://wiki.hudson-ci.org//download/attachments/753667/1.png" alt="hudson" width="436" height="338"/><br />
There are a number of continuous integration packages for Ruby software including CI Joe, CruiseControl.rb. I chose Hudson because it is extendable via plugins and has great support for running automated testing for non-ruby software as well.</p>
<h3>Install hudson and jetty:</h3>
<p><a href="http://hudson-ci.org/">Hudson</a> itself is a self contained Java servlet. You can either run it in a servlet container like jetty by sticking <a href="http://hudson-ci.org/latest/hudson.war">hudson.war</a> into the webapps directory or just running it using java -jar hudson.war</p>
<p>On your testing server:</p>
<p>Set a working dir:<br />
<code><br />
export HUDSON_HOME=/data/apps/test/hudson<br />
</code></p>
<p>Install ci_reporter:<br />
<code><br />
sudo gem install ci_reporter<br />
</code><br />
Install plugins:<br />
<code><br />
cd /data/apps/test/hudson/plugins<br />
wget http://hudson-ci.org/latest/ruby.hpi<br />
wget http://hudson-ci.org/latest/git.hpi<br />
wget http://hudson-ci.org/latest/rake.hpi<br />
wget http://hudson-ci.org/latest/rubyMetrics.hpi<br />
</code></p>
<h3>Setting up a Project in Hudson</h3>
<p>We can follow these tasks to create a CI job for a Ruby on Rails 3.0 project.<br />
Hudson will be accessible from http://localhost:8080 or http://localhost:8080/hudson if you used a servlet container.</p>
<p>Click &#8216;New Job&#8217;<br />
Click &#8216;Build a free-style software project&#8217;<br />
This lets you use a custom ruby app.</p>
<p>On the project configuration page:<br />
set the git repo and the option to poll SCM<br />
Add a Execute Shell option with:<br />
<code><br />
bundle install<br />
</code><br />
This will install all the necessary gems from the Gemfile.</p>
<p>Finally, add the rake task for the actual testing itself.<br />
Invoke Rake<br />
<code><br />
ci:setup:testunit<br />
test<br />
CI_REPORTS=results<br />
RAILS_ENV=staging<br />
</code></p>
<p>You can test the setup by clicking the &#8220;Build Now&#8221; link. In the future, the &#8220;Poll SCM&#8221; will just run your tests on a set interval whenever code is pushed to your git repo.</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2010/08/setting-up-a-hudson-continuous-integration-testing-server-for-rubyand-rails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Call a JRuby method from Java</title>
		<link>http://tommy.chheng.com/index.php/2010/06/call-a-jruby-method-from-java/</link>
		<comments>http://tommy.chheng.com/index.php/2010/06/call-a-jruby-method-from-java/#comments</comments>
		<pubDate>Sun, 20 Jun 2010 19:26:23 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[jruby]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=315</guid>
		<description><![CDATA[JRuby is a great way of reducing verbose Java code. Here&#8217;s a way of implementing a Java interface in JRuby and calling the method from Java. Java Interface We&#8217;ll start with a simple Java interface: interface JavaInterfaceExample{ int add(int a, int b); } Compile it using javac JavaInterfaceExample.java Implement the Java Interface in JRuby We [...]]]></description>
			<content:encoded><![CDATA[<p>JRuby is a great way of reducing verbose Java code. Here&#8217;s a way of implementing a Java interface in JRuby and calling the method from Java.</p>
<h3>Java Interface</h3>
<p>We&#8217;ll start with a simple Java interface:</p>
<pre>
<code>
interface JavaInterfaceExample{
  int add(int a, int b);
}
</code>
</pre>
<p>Compile it using<br />
<code><br />
javac JavaInterfaceExample.java<br />
</code></p>
<h3>Implement the Java Interface in JRuby</h3>
<p>We will implement this method in JRuby. When importing interfaces from Java code, you should use the Java namespace as in include Java::JavaInterfaceExample. The signature is important since JRuby is dynamically typed. If it isn&#8217;t specified, the parameters will be a Java Object.</p>
<pre>
<code>
require 'java'
class JrubyAdderImpl
  include Java::JavaInterfaceExample
  java_signature 'int add(int, int)'
	def add(a, b)
		a+b
	end
end
</code>
</pre>
<p>Compile it using:<br />
<code><br />
jrubyc --javac -cp . JrubyAdderImpl.rb<br />
</code></p>
<h3>Creating a Java class calling a JRuby method</h3>
<p>Then let&#8217;s create a Java class which calls the jruby method:</p>
<pre>
<code>
class JavaCallerApp {
    public static void main(String[] args) {
	    JrubyAdderImpl jrubyImpl = new JrubyAdderImpl();
	    System.out.println("Adding 3+5=" + jrubyImpl.add(3,5)); // Display the string.
    }
}
</code>
</pre>
<p>Compile it:<br />
<code><br />
javac -cp /usr/local/jruby/lib/jruby.jar:. JavaCallerApp.java<br />
</code></p>
<p>and run it:<br />
<code><br />
java -cp /usr/local/jruby/lib/jruby.jar:. JavaCallerApp<br />
</code></p>
<p>Output:<br />
<code><br />
Adding 3+5=8<br />
</code></p>
<h3>Downside</h3>
<p>While this works, it&#8217;s not a very optimally solution for calling JRuby code from Java. When you compiled JrubyAdderImpl.rb, it created a JrubyAdderImpl.java file which runs a JRuby runtime layer against the JRuby script file. I imagine this isn&#8217;t very performant. </p>
<p>I recommend using <a href="http://www.mirah.org/">Mirah</a> or <a href="http://www.scala-lang.org/">Scala</a> as alternative JVM languages for greater interoperability with Java.</p>
<p>I placed the code on a <a href="http://github.com/tc/call-jruby-from-java-example">github repo</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2010/06/call-a-jruby-method-from-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paypal Adaptive Ruby Gem Released</title>
		<link>http://tommy.chheng.com/index.php/2009/12/paypal-adaptive-ruby-gem-released/</link>
		<comments>http://tommy.chheng.com/index.php/2009/12/paypal-adaptive-ruby-gem-released/#comments</comments>
		<pubDate>Tue, 29 Dec 2009 19:27:24 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[paypal]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=188</guid>
		<description><![CDATA[I have been tinkering with the new Paypal Adaptive Payments API and created a simple ruby gem to interface with it. Still pretty new but I&#8217;m using it with little problems so far. Submit bug reports if found. See the code at github Paypal Adaptive Payments API The adaptive payments api gives you the opportunity [...]]]></description>
			<content:encoded><![CDATA[<p>I have been tinkering with the new Paypal Adaptive Payments API and created a simple ruby gem to interface with it. Still pretty new but I&#8217;m using it with little problems so far. Submit bug reports if found. See the code at <a href="http://github.com/tc/paypal_adaptive">github</a></p>
<p><strong>Paypal Adaptive Payments API</strong><br />
The adaptive payments api gives you the opportunity to make preapproved payments, chained payments and parallel payments.  The chained/parallel payments are great for commission-based apps or if you are trying to connect  a buyer to multiple sellers with a single interface.</p>
<p><strong>How to use with Rails:</strong><br />
Install:<br />
<code><br />
sudo gem install paypal_adaptive<br />
</code><br />
Setup your API info by adding a paypal_adaptive.yml to your config folder:</p>
<pre><code>
development:
  environment: "sandbox"
  username: "sandbox_username"
  password: "sandbox_password"
  signature: "sandbox_signature"
  application_id: "sandbox_app_id"

test:
  environment: "sandbox"
  username: "sandbox_username"
  password: "sandbox_password"
  signature: "sandbox_signature"
  application_id: "sandbox_app_id"

production:
  environment: "production"
  username: "my_production_username"
  password: "my_production_password"
  signature: "my_production_signature"
  application_id: "my_production_app_id"
</code></pre>
<p>Make the payment request:</p>
<pre>
<code>
pay_request = PaypalAdaptive::Request.new

data = {
"returnUrl" => "http://testserver.com/payments/completed_payment_request",
"requestEnvelope" => {"errorLanguage" => "en_US"},
"currencyCode"=>"USD",
"receiverList"=>{"receiver"=>
     [{"email"=>"testpp_1261697850_per@nextsprocket.com", "amount"=>"10.00"}]},
"cancelUrl"=>"http://testserver.com/payments/canceled_payment_request",
"actionType"=>"PAY",
"ipnNotificationUrl"=>"http://testserver.com/payments/ipn_notification"
}

pay_response = pay_request.pay(data)

if pay_response.success?
  redirect_to pay_response.approve_paypal_payment_url
else
  puts pay_response.errors.first['message']
  redirect_to failed_payment_url
end
</code>
</pre>
<p>Once the user goes to pay_response.approve_paypal_payment_url, they will be prompted to login to Paypal for payment.</p>
<p>Upon payment completion page, they will be redirected to http://testserver.com/payments/completed_payment_request.</p>
<p>They can also click cancel to go to http://testserver.com/payments/canceled_payment_request</p>
<p>The actual payment details will be sent to your server via &#8220;ipnNotificationUrl&#8221; You have to create a listener to receive POST messages from paypal. I added a Rails metal template in the templates folder which handles the callback.</p>
<p>Additionally, you can make calls to Paypal Adaptive&#8217;s other APIs:</p>
<pre>
<code>
payment_details, preapproval, preapproval_details,
cancel_preapproval, convert_currency, refund
</code>
</pre>
<p>Input is just a Hash just like the pay method. Refer to the <a href="https://www.x.com/docs/DOC-1531">Paypal Adaptive manual</a> for more details.</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/12/paypal-adaptive-ruby-gem-released/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Sorting a HashMap by Value in Java vs Ruby</title>
		<link>http://tommy.chheng.com/index.php/2009/12/sorting-a-hashmap-by-value-in-java-ruby/</link>
		<comments>http://tommy.chheng.com/index.php/2009/12/sorting-a-hashmap-by-value-in-java-ruby/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 16:40:15 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[hashmap]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=176</guid>
		<description><![CDATA[I&#8217;m working a graph problem in Java where I need to sort nodes by its edge count. I have a HashMap of nodes to edge count so I just need to sort a HashMap by its value. A quick Google search brought up a few solutions. Below is a snippet of a typical solution from [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working a graph problem in Java where I need to sort nodes by its edge count. I have a HashMap of nodes to edge count so I just need to sort a HashMap by its value.<br />
A quick Google search brought up a few solutions. Below is a snippet of a typical solution from <a href="http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java">StackOverFlow</a></p>
<pre>
<code>
public static <K, V extends Comparable<? super V>> List<K> getKeysSortedByValue(Map<K, V> map) {
    final int size = map.size();
    final List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(size);
    list.addAll(map.entrySet());
    final ValueComparator<V> cmp = new ValueComparator<V>();
    Collections.sort(list, cmp);
    final List<K> keys = new ArrayList<K>(size);
    for (int i = 0; i < size; i++) {
        keys.set(i, list.get(i).getKey());
    }
    return keys;
}
private static final class ValueComparator<V extends Comparable<? super V>>
                                     implements Comparator<Map.Entry<?, V>> {
    public int compare(Map.Entry<?, V> o1, Map.Entry<?, V> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
}
</code>
</pre>
<p>Can you believe it?? >10 lines of verbose madness! The Ruby solution is:<br />
<code><br />
>> x = {:a => 1, :b => 2, :c => 1, :d => 5}<br />
>> x.keys.sort_by{|k| x[k]}<br />
=> [:a, :c, :b, :d]<br />
</code></p>
<p>This makes you really appreciate closure support in languages. Java 7&#8242;s support of closure should bring more sanity to the Java world.</p>
<p>I&#8217;m also learning Clojure right now, the solution is just as nice as Ruby.<br />
<code><br />
user=> (def x {:a 1 :b 2 :c 1 :d 5})<br />
user=> (sort-by #(x %) (keys x))<br />
(:a :c :b :d)<br />
</code></p>
<p>edit:<br />
In Scala, it is also very succinct:</p>
<p><code><br />
scala> val x = Map('a' -> 1, 'b' -> 2, 'c' -> 1, 'd' -> 5)<br />
x: scala.collection.immutable.Map[Char,Int] = Map((a,1), (b,2), (c,1), (d,5))<br />
scala> x.keysIterator.toList.sortWith((key1,key2) => x(key1) < x(key2))<br />
res5: List[Char] = List(a, c, b, d)<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/12/sorting-a-hashmap-by-value-in-java-ruby/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Twitter OAuth Ruby Gem PIN-based Authentication API Change</title>
		<link>http://tommy.chheng.com/index.php/2009/08/twitter-oauth-ruby-gem-pin-based-authentication-api-change/</link>
		<comments>http://tommy.chheng.com/index.php/2009/08/twitter-oauth-ruby-gem-pin-based-authentication-api-change/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 19:08:07 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[oauth]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=139</guid>
		<description><![CDATA[I have been using the moomerman-twitter_oauth gem for to allow users to login to our web app via Twitter Connect. Unfortunately, it stopped working when a change in the Twitter API happened. During the OAuth authentication process, instead of being redirected back to our web app, it would show a screen that said: "You've successfully [...]]]></description>
			<content:encoded><![CDATA[<p>I have been using the moomerman-twitter_oauth gem for to allow users to login to our web app via Twitter Connect. Unfortunately, it stopped working when a change in the Twitter API happened. During the OAuth authentication process, instead of being redirected back to our web app, it would show a screen that said:</p>
<pre>"You've successfully granted access...enter the following PIN to complete the process"</pre>
<p>After browsing the net and getting help from the Twitter API team, I learned that Twitter recently made a change to their OAuth process to allow this PIN type authentication for applications.  See for more info: <a href="http://groups.google.com/group/twitter-development-talk/browse_thread/thread/472500cfe9e7cdb9/848f834227d3e64d?pli=1">http://groups.google.com/group/twitter-development-talk/browse_thread/thread/472500cfe9e7cdb9/848f834227d3e64d?pli=1</a></p>
<p>The oauth ruby gem defaults to using PIN-based process instead of the regular web app redirect process. To fix this, explicitly set the oauth_callback url parameter when getting the request token:</p>
<pre>    @twitter_client = TwitterOAuth::Client.new(
        :consumer_key =&gt; TWITTER_CONSUMER_KEY,
        :consumer_secret =&gt; TWITTER_CONSUMER_SECRET
    )
    request_token = @twitter_client.request_token(:oauth_callback =&gt; oauth_confirm_url)</pre>
<p>If you are getting a <em>(OAuth::Unauthorized) &#8220;401 Unauthorized&#8221;</em> error after adding the oauth_callback parameter, try altering your oauth callback method to explicitly state the oauth_verifier as well:</p>
<pre>
  def oauth_callback
    @twitter_client = TwitterOAuth::Client.new(
        :consumer_key => TWITTER_CONSUMER_KEY,
        :consumer_secret => TWITTER_CONSUMER_SECRET
    )

    @twitter_access_token = @twitter_client.authorize(
      session[:request_token],
      session[:request_token_secret],
      <img src='http://tommy.chheng.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> auth_verifier =>params[:oauth_verifier]
    )
</pre>
<p>Apparently, this was <a href="http://groups.google.com/group/twitter-development-talk/browse_thread/thread/1c48fedf4ae7ed52/5ac22db230c7a95a?lnk=gst&#038;q=oauth+pin#5ac22db230c7a95a">posted</a> on the Twitter API Development Group in late May, but it would have been nice if Twitter DMed every web app signed up on the twitter app list of the change.  I guess this is a warning for any Twitter API consumers to follow the dev list closely..</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/08/twitter-oauth-ruby-gem-pin-based-authentication-api-change/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails 2.3.2 Upgrade Gotchas</title>
		<link>http://tommy.chheng.com/index.php/2009/06/ruby-on-rails-2-3-2-upgrade-gotchas/</link>
		<comments>http://tommy.chheng.com/index.php/2009/06/ruby-on-rails-2-3-2-upgrade-gotchas/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 07:53:31 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rails 2.3.2]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=115</guid>
		<description><![CDATA[While cleaning/re-factoring the PeopleJar codebase, we decided to make the move from Rails 2.2.2 to Rails 2.3.2. Rack integration was the biggest single &#8220;under the hood&#8221; change. Adam Wiggins of Heroku explains the benefits in his Rails Metal, Rack and Sinatra presentation from RailsConf. He has a great example of incorporating a Sinatra app with [...]]]></description>
			<content:encoded><![CDATA[<p>While cleaning/re-factoring the <a href="http://peoplejar.com">PeopleJar</a> codebase, we decided to make the move from Rails 2.2.2 to Rails 2.3.2. Rack integration was the biggest single &#8220;under the hood&#8221; change.  Adam Wiggins of Heroku explains the benefits in his <a href="http://adam.blog.heroku.com/past/2009/5/6/railsconf_slides_rails_metal_rack_sinatra/">Rails Metal, Rack and Sinatra presentation from RailsConf</a>.  He has a great example of incorporating a Sinatra app with a Rails app.</p>
<p>No upgrades would be complete without some incompatibilities. As noted on the <a href="http://guides.rubyonrails.org/2_3_release_notes.html">official Ruby on Rails release notes</a>, test Sessions, Cookies, File uploads, JSON/XML APIs. We found conflicts in the facebooker and ar-extensions gems. Luckily, the developers already pushed out fixes so you can just do a gem update.</p>
<p>There was one other cryptic error in one of our ajax calls:</p>
<pre>  Status: 500 Internal Server Error
  private method `split' called for #
    /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.3.2/lib/action_controller/mime_type.rb:206:in `method_missing'
    /opt/local/lib/ruby/gems/1.8/gems/rack-1.0.0/lib/rack/request.rb:51:in `media_type'
    /opt/local/lib/ruby/gems/1.8/gems/rack-1.0.0/lib/rack/request.rb:117:in `parseable_data?'
    /opt/local/lib/ruby/gems/1.8/gems/rack-1.0.0/lib/rack/request.rb:138:in `POST'
    /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.3.2/lib/action_controller/request.rb:428:in `request_parameters'</pre>
<p>We could fix this with some good old monkey patching! Add this to an initializer in your config/initializers directory. this is a <a href="https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2564-acrequestcontent_type-should-return-a-string">reported bug</a> at the rails lighthouse and should be fixed in the next release.</p>
<pre>module Mime
  class Type
    def split(*args)
      to_s.split(*args)
    end
  end
end</pre>
<p>Overall, the upgrade went pretty well: just a few gem upgrades and minor tweaks. If you are on Rails 2.2.2 or older, give the upgrade a shot! </p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/06/ruby-on-rails-2-3-2-upgrade-gotchas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Organizing Models in Rails without Namespacing</title>
		<link>http://tommy.chheng.com/index.php/2009/06/organizing-models-in-rails-without-namespacing/</link>
		<comments>http://tommy.chheng.com/index.php/2009/06/organizing-models-in-rails-without-namespacing/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 00:13:43 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=100</guid>
		<description><![CDATA[I was doing some code cleanup and noticed we have over 50 models in our models directory. Not good. The first thing I thought was to add namespacing. I googled the topic and turns out namespacing models is a bad idea because of how Rails collapses the model namespaces. Adding sub directories is a better [...]]]></description>
			<content:encoded><![CDATA[<p>I was doing some code cleanup and noticed we have over 50 models in our models directory. Not good. The first thing I thought was to add namespacing. I googled the topic and turns out namespacing models is a bad idea because of how Rails collapses the model namespaces. Adding sub directories is a better and cleaner solution. <a href="http://blog.hasmanythrough.com/2008/5/6/a-simple-alternative-to-namespaced-models">Read Josh Susser&#8217;s post on the topic</a>.</p>
<p>To use sub directories, you must add the directories to Rails&#8217; config.load_paths in your environment.rb</p>
<pre>
   config.load_paths << "#{Rails.root}/app/models/profile"
</pre>
<p>To make this more flexible, you can use this snippet to add all sub directories:</p>
<pre>
  #Add all sub directories in models to load paths
  Dir.entries("#{Rails.root}/app/models").each do |file|
    next if file.eql?('.') || file.eql?('..')
    full_path = "#{Rails.root}/app/models/#{file}"
    config.load_paths << full_path if File.directory?(full_path)
  end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/06/organizing-models-in-rails-without-namespacing/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Easy Javascript Validation with Javascript Lint For Rails Testing</title>
		<link>http://tommy.chheng.com/index.php/2009/06/javascript-validation-lint-for-rails/</link>
		<comments>http://tommy.chheng.com/index.php/2009/06/javascript-validation-lint-for-rails/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 05:15:32 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=76</guid>
		<description><![CDATA[I found this great Javascript Lint tool. It checks for common(missing semicolons) and not so common(use of the void type) javascript errors. A full featured Selenium test suite would be the ideal for full javascript testing coverage but Javascript Lint is a no hassle addition. I wrote a simple Rails integration test case to scan [...]]]></description>
			<content:encoded><![CDATA[<p>I found this great<a href="http://www.javascriptlint.com/"> Javascript Lint tool</a>. It checks for common(missing semicolons) and not so common(use of the void type) javascript errors. A full featured Selenium test suite would be the ideal for full javascript testing coverage but Javascript Lint is a no hassle addition.</p>
<p>I wrote a simple Rails integration test case to scan all the javascript files in the public/javascripts folder. Download the javascript lint tool and add the file below to your integration test suite. You easily adapt this to Rspec if you would like.</p>
<pre><code>
require 'test_helper'

class JavascriptTest < ActionController::IntegrationTest
  # Download jsl from http://www.javascriptlint.com and add the jsl to your PATH environment variable
  def setup
    @js_paths = File.join(Rails.root, 'public', 'javascripts', '*.js')
  end

  test "validate javascript files for errors" do
    Dir[@js_paths].each do |js_path|
      output = %x[jsl -process #{js_path}]

      is_valid_js_file = output.include?("0 error(s)") ?  true : false
      assert(is_valid_js_file, "JSLint on #{js_path} should return no errors: \n #{output}")
    end
  end
end
</code></pre>
<p>Here's an example of the error output:</p>
<pre>
<code>
  2) Failure:
test_validate_javascript_files_for_errors(JavascriptTest)
    [/test/integration/javascript_test.rb:14:in `test_validate_javascript_files_for_errors'
     /test/integration/javascript_test.rb:10:in `each'
     /test/integration/javascript_test.rb:10:in `test_validate_javascript_files_for_errors']:
JSLint on ..../public/javascripts/application.js should return no errors:
 JavaScript Lint 0.3.0 (JavaScript-C 1.5 2004-09-24)
Developed by Matthias Miller (http://www.JavaScriptLint.com)

application.js
.../public/javascripts/application.js(3): lint warning: missing semicolon
        num = ;
........^
</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/06/javascript-validation-lint-for-rails/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Deploying a Sinatra app on Nginx/Passenger with Capistrano and Git</title>
		<link>http://tommy.chheng.com/index.php/2009/06/deploying-a-sinatra-app-on-nginx-passenger-with-capistrano-and-git/</link>
		<comments>http://tommy.chheng.com/index.php/2009/06/deploying-a-sinatra-app-on-nginx-passenger-with-capistrano-and-git/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 16:50:31 +0000</pubDate>
		<dc:creator>tommy</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://tommy.chheng.com/?p=48</guid>
		<description><![CDATA[Need a quick web app done in Ruby? While Ruby on Rails is a great framework, it is overkill for a simple one page application. Enter: Sinatra. Sinatra is a light-weight Ruby framework intended for fast web applications. In fact, here is all you need for a hello world app: # myapp.rb require 'rubygems' require [...]]]></description>
			<content:encoded><![CDATA[<p>Need a quick web app done in Ruby? While Ruby on Rails is a great framework, it is overkill for a simple one page application. Enter: Sinatra.</p>
<p>Sinatra is a light-weight Ruby framework intended for fast web applications. In fact, here is all you need for a hello world app:</p>
<blockquote><p><code><br />
# myapp.rb<br />
require 'rubygems'<br />
require 'sinatra'<br />
get '/' do<br />
'Hello world!'<br />
end<br />
</code></p></blockquote>
<p><a href="http://www.sinatrarb.com/documentation.html">You can read more about Sinatra syntax on their documentation page.</a></p>
<p>This guide will get you started from the ground up to setting up and deploying a sinatra app on Nginx/Passenger with Capistrano and Git. I choose Passenger because it allows you to run multiple ruby applications easier than the traditional Mongrel setup.</p>
<h2>Install Passenger/Nginx</h2>
<p>Install the passenger gem:<br />
<code>gem install passenger</code></p>
<p>Install Nginx and Passenger Module:<br />
<code>passenger-install-nginx-module</code></p>
<p>The instructions from the install scripts are pretty much self-explanatory. More information on the <a href="http://www.modrails.com/install.html">official Phusion Passenger page</a>. I also recommend installing Phusion&#8217;s Ruby Enterprise Edition for more memory savings.</p>
<p>Make sure your nginx.conf file is configured to include external files, notice the include statements at the end:</p>
<blockquote><p><code><br />
user deploy;<br />
worker_processes  1;<br />
error_log  /var/log/nginx/error.log;<br />
pid        /var/run/nginx.pid;<br />
events {<br />
worker_connections  1024;<br />
}<br />
http {<br />
include       /opt/nginx/conf/mime.types;<br />
default_type  application/octet-stream;<br />
passenger_root  /opt/ruby-enterprise-1.8.6-20090421/lib/ruby/gems/1.8/gems/passenger-2.2.2;<br />
passenger_ruby  /usr/bin/ruby;<br />
passenger_max_pool_size     2;<br />
access_log  /var/log/nginx/access.log;<br />
sendfile        on;<br />
keepalive_timeout  65;<br />
tcp_nodelay        on;<br />
gzip  on;<br />
server_names_hash_bucket_size 128;<br />
include /opt/nginx/conf/conf.d/*.conf;<br />
include /opt/nginx/conf/sites-enabled/*;<br />
}<br />
</code></p></blockquote>
<p>Create a Nginx entry file in /opt/nginx/conf/sites-available/APP_NAME:</p>
<blockquote><p><code><br />
server {<br />
listen 80;<br />
server_name YOURDOMAINNAME.HERE;<br />
root /u/apps/production/APP_NAME/current/public;<br />
passenger_enabled on;<br />
}<br />
</code></p></blockquote>
<p>Symlink this in the sites-enabled folder:<br />
<code><br />
ln -s /opt/nginx/conf/sites-available/APP_NAME /opt/nginx/conf/sites-enabled/APP_NAME<br />
</code></p>
<h2>A basic Sinatra template</h2>
<p>Now, let&#8217;s get a basic Sinatra app on the server. To speed things along, clone this Sinatra template app:<br />
<code>git clone git://github.com/tc/sinatra-template.git</code></p>
<p>This includes a Rack config file(config.ru) and a cap deploy script.</p>
<p>This was forked from <a href="http://github.com/zapnap/sinatra-template/tree/master">zapnap/sinatra-template</a> but I removed datamapper since I didn&#8217;t intend to use a database. I also added a cap template script.</p>
<p>Edit the deploy.rb file and add in your git url/username/app_name</p>
<blockquote><p><code><br />
#========================<br />
#CONFIG<br />
#========================<br />
set :application, "APP_NAME"<br />
set :scm, :git<br />
set :git_enable_submodules, 1<br />
set :repository, "GIT_URL"<br />
set :branch, "master"<br />
set :ssh_options, { :forward_agent =&gt; true }<br />
set :stage, :production<br />
set :user, "deploy"<br />
set :use_sudo, false<br />
set :runner, "deploy"<br />
set :deploy_to, "/u/apps/#{stage}/#{application}"<br />
set :app_server, :passenger<br />
set :domain, "DOMAIN_URL"<br />
#========================<br />
#ROLES<br />
#========================<br />
role :app, domain<br />
role :web, domain<br />
role :db, domain, :primary =&gt; true<br />
#========================<br />
#CUSTOM<br />
#========================<br />
namespace :deploy do<br />
task :start, :roles =&gt; :app do<br />
run "touch #{current_release}/tmp/restart.txt"<br />
end<br />
task :stop, :roles =&gt; :app do<br />
# Do nothing.<br />
end<br />
desc "Restart Application"<br />
task :restart, :roles =&gt; :app do<br />
run "touch #{current_release}/tmp/restart.txt"<br />
end<br />
end<br />
</code></p></blockquote>
<h2>Deploying to Server</h2>
<p>Let&#8217;s deploy the app onto the server now. I will assume you already have ssh key authentication setup on the server.</p>
<p>Now, setup your directories using<br />
<code><br />
cap deploy:setup<br />
</code></p>
<p>and deploy your code from your git repo.<br />
<code><br />
cap deploy<br />
</code></p>
<p>That&#8217;s it! Passenger is able to recognize Sinatra app through the RACK interface. You should be able to visit the domain and see your app up:<br />
<img src="http://tommy.chheng.com/wp-content/uploads/2009/06/Picture-3.png" alt="sinatra_template" title="sinatra_template" width="527" height="189" class="alignnone size-full wp-image-73" /></p>
<p> The cap script will automatically restart the app by touching the restart.txt file.</p>
]]></content:encoded>
			<wfw:commentRss>http://tommy.chheng.com/index.php/2009/06/deploying-a-sinatra-app-on-nginx-passenger-with-capistrano-and-git/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
