<?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>A Waage Blog</title>
	<atom:link href="http://qugstart.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://qugstart.com/blog</link>
	<description>Ruby, Rails, Life</description>
	<lastBuildDate>Thu, 10 Nov 2011 00:35:02 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Ruby floats, BigDecimals and money (currency)</title>
		<link>http://qugstart.com/blog/ruby-and-rails/ruby-floats-bigdecimals-and-money-currency/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/ruby-floats-bigdecimals-and-money-currency/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 00:29:22 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[RSpec]]></category>
		<category><![CDATA[Rails Testing]]></category>
		<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[BigDecimals]]></category>
		<category><![CDATA[currency]]></category>
		<category><![CDATA[Floats]]></category>
		<category><![CDATA[money]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=151</guid>
		<description><![CDATA[Fellow Ruby-ers, please be warned!!! DO NOT use Ruby floats when performing arithmetic calculations involving money!
My calculations work in IRB, so I was really confused when I ran into this weird situation where (what I thought was) a simple arithmetic calculation led to strange results in my unit tests (I cannot stress the importance of [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Fellow Ruby-ers, please be warned!!! DO NOT use Ruby floats when performing arithmetic calculations involving money!</strong></p>
<p>My calculations work in IRB, so I was really confused when I ran into this weird situation where (what I thought was) a simple arithmetic calculation led to strange results in my unit tests (I cannot stress the importance of good unit testing!).</p>
<p>My backend calculation was basically this (simplified):</p>
<pre lang='ruby' class='prettyprint'>
# arbitrary amounts for these two variables
percentage = 12
total_in_cents = 400

discount = percentage.to_f / 100.0
total_in_float = total_in_cents.to_f * 100.0
new_price = (total_in_float * discount ).round / 100
</pre>
<p>Now, it&#8217;s pretty obvious that 12% of (400 cents) $4.00 should just be $0.48 (48 cents)<br />
However, my barrage of unit tests kept producing strange results where a simple calculation was returning incorrect results. Doing some research, I discovered a series of articles worth reading including:</p>
<ul>
<li> <a href="https://makandracards.com/makandra/1505-invoices-how-to-properly-round-and-calculate-totals">How to properly round and calculate totals</a> </li>
<li><a href="https://makandracards.com/makandra/1178-bigdecimal-arithmetic-in-ruby">BigDecimal arithmetic in Ruby</a></li>
</ul>
<p>Also, check out the <a href="https://github.com/collectiveidea/money">Money gem</a> &#8211; I&#8217;ve never used it personally, but <a href="http://stackoverflow.com/questions/1019939/ruby-on-rails-best-method-of-handling-currency-money">people have said good things about it</a>. </p>
<p>Heeding the advice I found online, I re-wrote all my money-related calculations using BigDecimals instead of Floats.</p>
<pre lang='ruby' class='prettyprint'>
percentage = 12
total_in_cents = 400
discount = BigDecimal(percentage.to_s) / 100
total_in_float = BigDecimal(total_in_cents.to_s) * 100
new_price = (total_in_float * discount ).to_i / 100
</pre>
<p>After switching over from Floats to BigDecimals, my unit tests all passed!<br />
Lesson learned and hope this heads-up helps you guys too. </p>
<p><strong>Summary:</strong><br />
<strong>Use BigDecimals for money calculations and remember to write good UNIT TESTS!!</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/ruby-floats-bigdecimals-and-money-currency/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Git &#8211; Push a branch to remote repository</title>
		<link>http://qugstart.com/blog/git-and-svn/git-push-a-branch-to-remote-repository/</link>
		<comments>http://qugstart.com/blog/git-and-svn/git-push-a-branch-to-remote-repository/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 20:23:00 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[Git and SVN]]></category>
		<category><![CDATA[branch]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[push]]></category>
		<category><![CDATA[remote]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=145</guid>
		<description><![CDATA[So you just created a new branch locally. You put in 200 hours into this branch, and then realize that the only copy of all these changes is on your MacBook! Don&#8217;t get scared, just push the branch to your remote server.
It&#8217;s easy:

$> git push -u &#60;remote-name&#62; &#60;branch-name&#62;

Or, usually:

$> git push -u origin branch-name

]]></description>
			<content:encoded><![CDATA[<p>So you just created a new branch locally. You put in 200 hours into this branch, and then realize that the only copy of all these changes is on your MacBook! Don&#8217;t get scared, just push the branch to your remote server.</p>
<p>It&#8217;s easy:</p>
<pre class='prettyprint' lang='bash'>
$> git push -u &lt;remote-name&gt; &lt;branch-name&gt;
</pre>
<p>Or, usually:</p>
<pre class='prettyprint' lang='bash'>
$> git push -u origin branch-name
</pre>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/git-and-svn/git-push-a-branch-to-remote-repository/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails 3 RSpec Request Spec &#8211; Testing Subdomains</title>
		<link>http://qugstart.com/blog/ruby-and-rails/rails-3-rspec-request-spec-testing-subdomains/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/rails-3-rspec-request-spec-testing-subdomains/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 22:43:56 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[RSpec]]></category>
		<category><![CDATA[Rails Testing]]></category>
		<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[Rails 3]]></category>
		<category><![CDATA[Subdomains]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=138</guid>
		<description><![CDATA[How do you test sub-domains in RSpec Request specs (integration tests) ???

# Pass it into the GET request!
get '/programs/100', nil, {'HTTP_HOST' => 'sub.domain.com'}

The 3rd parameter to the get method is a hash of HTTP headers.
See the Rails API documentation for details.
Note:
Depending on the type of test you are working with (support / controller / request [...]]]></description>
			<content:encoded><![CDATA[<p>How do you test sub-domains in RSpec Request specs (integration tests) ???</p>
<pre class='prettyprint' lang='ruby'>
# Pass it into the GET request!
get '/programs/100', nil, {'HTTP_HOST' => 'sub.domain.com'}
</pre>
<p>The 3rd parameter to the get method is a hash of HTTP headers.<br />
See the <a href="http://api.rubyonrails.org/classes/ActionDispatch/Integration/RequestHelpers.html#method-i-get">Rails API documentation</a> for details.</p>
<p>Note:<br />
Depending on the type of test you are working with (support / controller / request / integration etc.) you pass in the sub domain differently.</p>
<p>Here&#8217;s some good reference posts on Stack Overflow for setting subdomains in <strong>controller</strong> specs:<br />
1. <a href="http://stackoverflow.com/questions/2556627/rails-rspec-set-subdomain">Rails RSpec Set Subdomain</a></p>
<pre class='prettyprint' lang='ruby'>
# Set the @request.host in a before block
before(:each) do
  @request.host = "#{mock_subdomain}.example.com"
end
</pre>
<p>2. <a href="http://stackoverflow.com/questions/6033717/my-rails-3-applicaiton-has-to-have-a-subdomain-to-work-my-rspec-controller-test">Subdomains in RSpec Controller Tests</a></p>
<pre class='prettyprint' lang='ruby'>
 # I haven't tried this, and not sure you would need to mock out the current_subdomain method.
  @subdomain = 'sub.domain.com'
  controller.expects(:current_subdomain).returns(@subdomain)
  @request.host = "#{@subdomain}.test.host"
</pre>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/rails-3-rspec-request-spec-testing-subdomains/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RSpec &#8211; Running One Single Test at a Time</title>
		<link>http://qugstart.com/blog/ruby-and-rails/rspec-running-one-test-at-a-time/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/rspec-running-one-test-at-a-time/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 22:03:21 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[RSpec]]></category>
		<category><![CDATA[Rails Testing]]></category>
		<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[single test]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=130</guid>
		<description><![CDATA[In the old days I would pass a regular expression to run a particular unit test or group of similarly named unit tests by name.
Here&#8217;s the easy way to run one test in RSpec&#8230; by line number!
Look at the line-number of any RSpec block (it, describe, etc), and simply run the rspec command, passing in [...]]]></description>
			<content:encoded><![CDATA[<p>In the old days I would pass a regular expression to run a particular unit test or group of similarly named unit tests by name.</p>
<p>Here&#8217;s the easy way to run one test in RSpec&#8230; by line number!<br />
Look at the line-number of any RSpec block (it, describe, etc), and simply run the rspec command, passing in the [filename]:[line number]:</p>
<pre class='prettyprint' lang='bash'>
$ rspec models/user_spec.rb:27
</pre>
<p>Happy testing!</p>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/rspec-running-one-test-at-a-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails Rotating Log Files with logrotate</title>
		<link>http://qugstart.com/blog/ruby-and-rails/rails-rotating-log-files-with-logrotate/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/rails-rotating-log-files-with-logrotate/#comments</comments>
		<pubDate>Wed, 15 Jun 2011 18:56:54 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[log file rotation]]></category>
		<category><![CDATA[logger]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=122</guid>
		<description><![CDATA[I know there&#8217;s a way to specify Rails log rotation parameters directly in the app. This works for some people:

# Can place this in environment.rb
# 2nd argument - number of log files to keep
# 3rd argument - size (bytes) that log files are allowed to reach before rotation
config.logger = Logger.new(config.log_path, 8, 1024)

However&#8230;. I like the [...]]]></description>
			<content:encoded><![CDATA[<p>I know there&#8217;s a way to specify Rails log rotation parameters directly in the app. This works for some people:</p>
<pre class='prettyprint' lang='ruby'>
# Can place this in environment.rb
# 2nd argument - number of log files to keep
# 3rd argument - size (bytes) that log files are allowed to reach before rotation
config.logger = Logger.new(config.log_path, 8, 1024)
</pre>
<p>However&#8230;. I like the customizability of using <strong>logrotate</strong> better!<br />
Here&#8217;s my logrotate config file that handles weekly log rotation, delayed compression and uses the copy-truncate method:</p>
<p>I place this config in the /etc/logrotate.d folder (ubuntu)<br />
(ie. /etc/logrotate.d/&lt;rails_app_name&gt;)</p>
<pre class='prettyprint' lang='bash'>
/var/www/rails/<rails_app_name>/shared/log/production.log {
  weekly
  missingok
  rotate 8
  compress
  delaycompress
  notifempty
  copytruncate
}
</pre>
<p>This config will rotate my production.log file weekly, keeping at most 8 log files. It delays compression until next rotation (extra precaution, simply to make sure the log file is not in use), and uses the &#8216;copytruncate&#8217; method which basically copies the current log file, and then truncates this log file, so the Rails app maintains file pointer for continued writing.</p>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/rails-rotating-log-files-with-logrotate/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>RSpec Request Spec to Test Rails / Grape API Functionality</title>
		<link>http://qugstart.com/blog/ruby-and-rails/rspec-request-spec-to-test-rails-grape-api-functionality/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/rspec-request-spec-to-test-rails-grape-api-functionality/#comments</comments>
		<pubDate>Thu, 26 May 2011 08:29:08 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[RSpec]]></category>
		<category><![CDATA[Rails Testing]]></category>
		<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Basic Authentication]]></category>
		<category><![CDATA[basic_auth]]></category>
		<category><![CDATA[Grape]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[request]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=106</guid>
		<description><![CDATA[I finally got around to trying Grape &#8211; a &#8220;RESTful API microframework built to easily and quickly produce APIs for Ruby-based web applications&#8221;. This is a project still in baby stages, but has a lot of potential and worth exploring for anyone creating a Rack-based API in Ruby, not necessarily Rails!
Now, after creating a pretty [...]]]></description>
			<content:encoded><![CDATA[<p>I finally got around to trying <a href="https://github.com/intridea/grape/wiki">Grape</a> &#8211; a &#8220;RESTful API microframework built to easily and quickly produce APIs for Ruby-based web applications&#8221;. This is a project still in baby stages, but has a lot of potential and worth exploring for anyone creating a Rack-based API in Ruby, not necessarily Rails!</p>
<p>Now, after creating a pretty basic API that used HTTP Basic Authentication, I was inclined to write some RSpec tests to make sure my API was working the way I thought it was (.. or because I am obsessed with well-tested, beautiful code..). </p>
<p>After some thought, I decided that the best way to test my API was with <a href="http://relishapp.com/rspec/rspec-rails/v/2-6/dir/request-specs/request-spec">RSpec &#8220;request&#8221; specs</a>. Now, if you are at all relatively new to RSpec (I was a Test::Unit kinda guy before), it might not be completely obvious that &#8220;request specs&#8221; are basically what I have come to know as &#8220;integration tests&#8221;, testing high-level functionality that spans multiple controllers and multiple requests &#8211; (think: a user&#8217;s interaction with the app).  </p>
<p>My reasoning for choosing request specs is because I want to test specific API URL endpoints routed the way I expected. (Routing is handled magically by Grape with a simple mount in the config/routes.rb file). API testing just kinda makes sense to handle in request specs.</p>
<p>Anyways, I ran into a couple issues because in REQUEST specs, you do not have access to the @request object (haha?), as you do in controller specs. Now, in order to mock HTTP Basic Authentication, you need to mock the request object to send headers along with the GET request. </p>
<p>Well, solution: It turns out you can pass headers into your get() method! I only wish I had discovered that an hour ago!</p>
<p>Here&#8217;s a simple excerpt from my API request specs that shows how to mock the HTTP basic authentication and test your API functionality:</p>
<p>With NO basic auth, it&#8217;s just a simple GET request</p>
<pre class="prettyprint" lang="ruby">
  it 'should return a 401 with no basic auth to /api/v1/rewards' do
    get '/api/v1/rewards'
    response.code.should == '401'
    response.body.should == "Unauthorized - Please check your username and password"
  end
</pre>
<p>To mock the basic auth, simply pass header hash as argument to the GET request! No need to access the request object here.</p>
<pre class="prettyprint" lang="ruby">
  it 'should return a 200 with valid basic auth to /api/v1/rewards' do
    # Uses basic_auth helper method
    credentials = basic_auth('testuser','test')
    get '/api/v1/rewards', nil, {'HTTP_AUTHORIZATION' =>  credentials }
    response.code.should == '200'
    response.body.should == "..."
  end

# You can define this at the bottom of your spec file, or in spec_helper for convenience
def basic_auth(user, password)
  ActionController::HttpAuthentication::Basic.encode_credentials user, password
end
</pre>
<p>Hope this helps someone else. Now go write some request specs! <img src='http://qugstart.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/rspec-request-spec-to-test-rails-grape-api-functionality/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Create a link in Javascript with the .link method</title>
		<link>http://qugstart.com/blog/javascript/create-a-link-in-javascript-with-the-link-method/</link>
		<comments>http://qugstart.com/blog/javascript/create-a-link-in-javascript-with-the-link-method/#comments</comments>
		<pubDate>Sun, 22 May 2011 19:11:50 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[href]]></category>
		<category><![CDATA[link]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=97</guid>
		<description><![CDATA[Now I don&#8217;t claim to be a Javascript expert, but I thought I knew the basics pretty well! Here&#8217;s a little-known method built into Strings that creates a link tag: 
html = 'click me'.link('http://example.com')
which results in:
html = '&#60;a href="http://example.com"&#62;click me&#60;/a&#62;'
]]></description>
			<content:encoded><![CDATA[<p>Now I don&#8217;t claim to be a Javascript expert, but I thought I knew the basics pretty well! Here&#8217;s a little-known method built into Strings that creates a link tag: </p>
<pre class='prettyprint' lang='javascript'>html = 'click me'.link('http://example.com')</pre>
<p>which results in:</p>
<pre class='prettyprint' lang='html'>html = '&lt;a href="http://example.com"&gt;click me&lt;/a&gt;'</pre>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/javascript/create-a-link-in-javascript-with-the-link-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wordpress Plugin &#8211; track referrers based on url GET parameters using regular expressions</title>
		<link>http://qugstart.com/blog/wordpress/wordpress-plugin-track-referrers-based-on-url-get-parameters-using-regular-expressions/</link>
		<comments>http://qugstart.com/blog/wordpress/wordpress-plugin-track-referrers-based-on-url-get-parameters-using-regular-expressions/#comments</comments>
		<pubDate>Fri, 25 Mar 2011 00:37:03 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[GET parameters]]></category>
		<category><![CDATA[query string]]></category>
		<category><![CDATA[referrals]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=88</guid>
		<description><![CDATA[First of all, all the credit and thanks to Marios Alexandrou for his wordpress plugin Social Media Alerts for Wordpress, which allows you to set up email notifications when certain query-strings are received to your wordpress site!
For example, if you wish to see when visitors come to your site from Twitter, you can specify a [...]]]></description>
			<content:encoded><![CDATA[<p>First of all, all the credit and thanks to Marios Alexandrou for his wordpress plugin <a href="http://www.mariosalexandrou.com/blog/social-media-email-alerts-for-wordpress/">Social Media Alerts for Wordpress</a>, which allows you to set up email notifications when certain query-strings are received to your wordpress site!</p>
<p>For example, if you wish to see when visitors come to your site from Twitter, you can specify a query string of &#8220;source=twitter&#8221;. When visitors come to your page with this parameter on the URL (ie. http://yoursite.com/?source=twitter) then this will be tracked, and you can be notified by email.</p>
<p>I installed this plugin but besides specifying the literal query-string, I wanted to be able to handle dynamic query-strings based on regular expressions that I could define. For example, I wanted to track all query-strings that matched &#8220;http://mysite.com?ref=..&#8221;. </p>
<p>This would track visits to anything where the query string matched &#8220;ref=&#8230;&#8221;. For example, &#8220;http://mysite.com?ref=twitter&#8221;, &#8220;http://mysite.com?ref=facebook&#8221;, &#8220;http://mysite.com?ref=digg&#8221;, etc.</p>
<p>Here&#8217;s my little bit of code to the plugin to support regular expressions :</p>
<pre class='prettyprint' lang='php'>
# File: social-media-email-alerts.php
# Line: 142
# Replace the existing "get_query" function definition with this:
  function get_query($qs){
          global $wra_sites;

          if ($qs) {
                  $query = explode("&#038;",$qs);

                  foreach($query as $query_string){
                          if(is_array($wra_sites[$query_string])){
                                  return $query_string;
                          }
                  }
                  # Added for regexp matching on query string
                  foreach($query as $query_string){
                          foreach($wra_sites as $key => $val){
                                  if (preg_match($key, $query_string) > 0) {
                                          return $key;
                                  }
                          }
                  }
          }
          return false;
  }
</pre>
<p>As you can see, it&#8217;s just a single foreach block that will match a query-string by regex, and return if found. Now it&#8217;s possible to add a rule for /^ref=.+/ that will alert me upon any match to this regular expression.</p>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/wordpress/wordpress-plugin-track-referrers-based-on-url-get-parameters-using-regular-expressions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ruby Multi-level Nested Hash Value</title>
		<link>http://qugstart.com/blog/uncategorized/ruby-multi-level-nested-hash-value/</link>
		<comments>http://qugstart.com/blog/uncategorized/ruby-multi-level-nested-hash-value/#comments</comments>
		<pubDate>Sat, 19 Mar 2011 03:27:22 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Hash]]></category>
		<category><![CDATA[initializers]]></category>
		<category><![CDATA[multi-level]]></category>
		<category><![CDATA[Nested]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=81</guid>
		<description><![CDATA[Often in my Ruby code or Rails application, I will need to find a value in a nested hash. Frequently this also comes in handy when dealing with JSON and parsing JSON to a hash. For example, I might have a hash of user information that looks like this:

user_hash = {:id => 1, :name => [...]]]></description>
			<content:encoded><![CDATA[<p>Often in my Ruby code or Rails application, I will need to find a value in a nested hash. Frequently this also comes in handy when dealing with JSON and parsing JSON to a hash. For example, I might have a hash of user information that looks like this:</p>
<pre class='prettyprint' lang='ruby'>
user_hash = {:id => 1, :name => 'John doe', :extra => {:birthday => {:month => 11, :day => 16, :year => 1951}}}
</pre>
<p>Now, when I want to find the birthday year, I have to do something messy like this:</p>
<pre class='prettyprint' lang='ruby'>
year = user_hash[:extra] &#038;&#038; user_hash[:extra][:birthday] &#038;&#038; user_hash[:extra][:birthday][:year]
</pre>
<p>How inconvenient is this?! Every level of the hash I am checking for existence of the hash-key. Here&#8217;s a helper method that I use so that I can avoid these verbose statements and get the value I want in 1 line. It adds a &#8216;hash_val&#8217; method to any hash, and takes in the hash-keys as arguments. If one of the nested hash keys is missing, it will simply return nil.</p>
<pre class='prettyprint' lang='ruby'>
# I usually define this in an initializer, so it can be used all over my app:
# Eg. Place in config/initializers/hash_val.rb
class Hash
  # Fetch a nested hash value
  def hash_val(*attrs)
    attr_count = attrs.size
    current_val = self
    for i in 0..(attr_count-1)
      attr_name = attrs[i]
      return current_val[attr_name] if i == (attr_count-1)
      return nil if current_val[attr_name].nil?
      current_val = current_val[attr_name]
    end
    return nil
  end
end
</pre>
<p>Now, getting a nested hash value is so easy!</p>
<pre class='prettyprint' lang='ruby'>
user_hash.hash_val(:extra, :birthday, :year)
 => 1951
</pre>
<p>And, if the hash-key does not exist, it simply returns nil:</p>
<pre class='prettyprint' lang='ruby'>
user_hash.hash_val(:extra, :trouble)
=> nil
</pre>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/uncategorized/ruby-multi-level-nested-hash-value/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rails 3 &#8211; How to Rename a Project</title>
		<link>http://qugstart.com/blog/ruby-and-rails/rails-3-how-to-rename-a-project/</link>
		<comments>http://qugstart.com/blog/ruby-and-rails/rails-3-how-to-rename-a-project/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 21:17:06 +0000</pubDate>
		<dc:creator>Andrew Waage</dc:creator>
				<category><![CDATA[Ruby and Rails]]></category>
		<category><![CDATA[grep]]></category>
		<category><![CDATA[rails3]]></category>
		<category><![CDATA[rename project]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://qugstart.com/blog/?p=78</guid>
		<description><![CDATA[As opposed to previous versions of Rails, Rails 3 namespaces your entire project according to your project name. As an example, notice that in your config/routes.rb file, the first line is:

ProjectName::Application.routes.draw do
...

This means that changing a project name involves changing a number of files to reference the new project name as well. Here&#8217;s a quick [...]]]></description>
			<content:encoded><![CDATA[<p>As opposed to previous versions of Rails, Rails 3 namespaces your entire project according to your project name. As an example, notice that in your config/routes.rb file, the first line is:</p>
<pre class='prettyprint' lang='ruby'>
ProjectName::Application.routes.draw do
...
</pre>
<p>This means that changing a project name involves changing a number of files to reference the new project name as well. Here&#8217;s a quick list of the standard files to change:</p>
<pre class='prettyprint' lang='bash'>
Rakefile
config.ru
config/application.rb
config/database.yml
config/environment.rb
config/environments/*.rb
config/initializers/secret_token.rb
config/initializers/session_store.rb
config/routes.rb</pre>
<p>Besides these, it&#8217;s a good idea to also check all files in config/ and config/initializers/<br />
If you want to be thorough, run this grep command in your project root, and you will get a list of all files that contain your old project name:</p>
<pre class='prettyprint' lang='bash'>
grep -Ri 'oldprojectame' * | cut -f1 -d':' | sort | uniq
</pre>
]]></content:encoded>
			<wfw:commentRss>http://qugstart.com/blog/ruby-and-rails/rails-3-how-to-rename-a-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

