
<?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>Cory Schires &#187; Ruby</title>
	<atom:link href="http://coryschires.com/tag/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://coryschires.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Sun, 01 Jan 2012 23:49:43 +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>How to shorten urls with bit.ly in Ruby on Rails.</title>
		<link>http://coryschires.com/how-to-shorten-urls-with-bit-ly-in-ruby-on-rails/</link>
		<comments>http://coryschires.com/how-to-shorten-urls-with-bit-ly-in-ruby-on-rails/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 00:20:44 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[bit.ly]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=307</guid>
		<description><![CDATA[Create retweet links with shortened urls in ruby on rails. Only requires two simple helper methods which you can cut-n-paste into your application.]]></description>
			<content:encoded><![CDATA[<p>First, let&#8217;s make a simple retweet link for our application. To keep our views a little cleaner, we&#8217;ll make a helper method in <span class="code_text">app/helpers/application_helper.rb</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def twitter_url(resource, tweet_text="Check out this article from my-site.com:")
          tweet_url = root_url.chop + url_for(resource)
          "http://twitter.com/home?status=#{tweet_text} #{tweet_url}"
        end
    </pre>
</div>
<p>This method just builds a url to twitter and supplies some default text which you may optionally override by passing a second argument. Call it in your view like this:</p>
<div class="code_block">
<pre class="brush: ruby;">
        <%= link_to "Retweet this post!", twitter_url(@post) %>
    </pre>
</div>
<p>Now, this method works but it would be much better if we could use shortened urls. So let&#8217;s change things a bit in order to use bit.ly &mdash; twitter&#8217;s preferred url shortening service. Before we write any code&#8230; </p>
<ol>
<li>You&#8217;ll need to <a href="http://bit.ly/account/register?rd=/">sign up for bit.ly</a>.</li>
<li>And <a href="http://bit.ly/account/your_api_key">grap your api key</a>.</li>
</ol>
<p>With that info on hand, we&#8217;re ready to interface with the bit.ly api. Let&#8217;s make another helper method also located in <span class="code_text">app/helpers/application_helper.rb</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def shorten_with_bitly(url)
          # build url to bitly api
          user = "insert-your-username"
          apikey = "insert-your-api-key"
          version = "2.0.1"
          bitly_url = "http://api.bit.ly/shorten?version=#{version}&#038;longUrl=#{url}&#038;login=#{user}&#038;apiKey=#{apikey}"

          # parse result and return shortened url
          buffer = open(bitly_url, "UserAgent" => "Ruby-ExpandLink").read
          result = JSON.parse(buffer)
          short_url = result['results'][url]['shortUrl']
        end
    </pre>
</div>
<p>This method uses your credentials to build a url to interface with the bit.ly api. Bitly receives our request and returns a JSON object containing a shortened url. We&#8217;ll parse this object, grab the shortened url, and return it.</p>
<p>Finally, we need to change our initial <span class="code_text">twitter_url</span> method to include url shortening:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def twitter_url(resource, tweet_text="Check out this article from my-site.com:")
          tweet_url = root_url.chop + url_for(resource)
          tweet_url = shorten_with_bitly(tweet_url) if Rails.env.production?

          "http://twitter.com/home?status=#{tweet_text} #{tweet_url}"
        end
    </pre>
</div>
<p>This is identical to our original method except we&#8217;ve added a new line which calls <span class="code_text">shorten_with_bitly</span>. This line overwrites the <span class="code_text">tweet_url</span> variable &mdash; replacing the long url with a shortened version. Finally, we&#8217;ll include a condition to ensure this only happens in production. This saves us from creating a bunch of useless bit.ly links that point to localhost urls.</p>
<h3>Some final points.</h3>
<ul>
<li>
        The <span class="code_text">shorten_with_bitly</span> method borrows heavily form a ruby snippet posted by <a href="http://puneetitengineer.wordpress.com/2009/07/27/minimise-url-in-ruby/">Puneet Pandey</a>. Pandey definitely deserves some credit here.
    </li>
<li>
        If you&#8217;re looking for a more robust way to interface with the bit.ly api, checkout this <a href="http://nasir.wordpress.com/2009/11/26/url-shortener-gem-bitly-api-wrapper-in-ruby/">url shortening gem</a> by Nasir Jamal. I&#8217;ve never used it but appears to be fully featured and well documented.
    </li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/how-to-shorten-urls-with-bit-ly-in-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>What&#8217;s the difference between .each and .collect?</title>
		<link>http://coryschires.com/whats-the-difference-between-each-and-collect/</link>
		<comments>http://coryschires.com/whats-the-difference-between-each-and-collect/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 20:36:20 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=151</guid>
		<description><![CDATA[What’s the difference between .each and .collect in ruby? This can be tricky...]]></description>
			<content:encoded><![CDATA[<p>What&#8217;s the difference between <span class="code_text">.each</span> and <span class="code_text">.collect</span> in ruby? This can be tricky because both methods work with a collection of objects.  The <span class="code_text">collect</span> method is simply a convenience method. Like the <span class="code_text">each</span> method, it iterates through objects in an array and somehow modifies them. But, unlike <span class="code_text">each</span>, it also stores these modified objects into a new array. If that sounds confusing&#8230;</p>
<h3 class="vag_post_header">Here&#8217;s an example.</h3>
<p>Let&#8217;s say you have an array:</p>
<div class="code_block">
<pre class="brush: ruby;">
		colors = %w{red yellow green blue orange purple pink teal}
	</pre>
</div>
<p>And you want to grab each object, uppercase it, and store the result in new array. You might try:</p>
<div class="code_block">
<pre class="brush: ruby;">
		big_colors = colors.each { |color| color.upcase }
	</pre>
</div>
<p>But this doesn&#8217;t work. It returns an array of lowercase colors because the code doesn&#8217;t know that we&#8217;d like to store each iteration in a new array. So lets refactor a bit and try this: </p>
<div class="code_block">
<pre class="brush: ruby;">
		big_colors = []
		colors.each do |color|
		  big_colors << color.upcase
		end
	</pre>
</div>
<p>That works. We create an empty array, grab each color, uppercase it, and add it our newly created array. </p>
<p>But because this is a fairly common process, ruby provides the <span class="code_text">collect</span> method to help clean things up a bit. So we can refactor this code using <span class="code_text">collect</span> like this:</p>
<div class="code_block">
<pre class="brush: ruby;">
		big_colors = colors.collect { |color| color.upcase }
	</pre>
</div>
<h3 class="vag_post_header">A few final points.</h3>
<ul>
<li>
		Although the <span class="code_text">collect</span> method works on arrays, it's not strictly an array method. It's part of the enumerable module which is mixed into to the array class. The enumerable module has loads of timesaving methods for working with collections. Check out the <a href="http://ruby-doc.org/core/classes/Enumerable.html">ruby documentation</a>.
	</li>
<li>
		The <span class="code_text">collect</span> method and the <span class="code_text">map</span> method are interchangeable. Most people prefer <span class="code_text">collect</span> but use whatever syntax makes more sense to you.
	</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/whats-the-difference-between-each-and-collect/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making jQuery and Rails play nice with AJAX.</title>
		<link>http://coryschires.com/making-jquery-and-rails-play-nice-with-ajax/</link>
		<comments>http://coryschires.com/making-jquery-and-rails-play-nice-with-ajax/#comments</comments>
		<pubDate>Sun, 13 Dec 2009 02:00:41 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=128</guid>
		<description><![CDATA[Rails has built in support for prototype but now most of us are using jQuery. I'll show you how to get Rails and jQuery working together with AJAX...]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need to observe for a client-side event (click, drag-n-drop, column resize, etc.) and store the result in your database. For example, say your application has customizable profile pages where users can rearrange, add, remove, and resize widgets (e.g. stock ticker, twitter feed, etc.).</p>
<p>Now, jQuery makes this functionality super easy &#8211; just a few lines of code. But here&#8217;s the tricky part: the configuration of each profile page needs to be stored in your database and be associated with a given user. Otherwise users would lose all their changes on page refresh. No good.</p>
<p>This means every time a user changes something (e.g. removes a stock ticker) you need to let rails know the profile has been changed so that the appropriate columns can be updated in your database (e.g. set the ticker&#8217;s &#8216;hidden&#8217; boolean to true). And ideally, this should all happen silently in the background so that the user&#8217;s not even aware their changes are being saved on the fly.</p>
<p>Now, we&#8217;re talking about making the client talk to the server without a page refresh. That means AJAX. So here&#8217;s the plan&#8230;</p>
<h3 class="vag_post_header">1. Create your javascript event.</h3>
<p>For simplicity, say you&#8217;d like to let the user can change the background color of their profile page. Let&#8217;s give them three buttons to toggle between red, yellow, and purple. Your html would look like this:</p>
<div class="code_block">
<pre class="brush: ruby;">
&lt;body&gt;
<div id="green" class="change_bg_color">Make Green</div>
<div id="yellow" class="change_bg_color">Make Yellow</div>
<div id="purple" class="change_bg_color">Make Purple</div>

&lt;/body&gt;
</pre>
</div>
<p>And your jQuery would look like this:</p>
<div class="code_block">
<pre class="brush: jscript;">
$('.change_bg_color').click(function() {
	if (this.id == 'green') { $('body').css('background-color', 'green') };
	if (this.id == 'yellow') { $('body').css('background-color', 'yellow') };
	if (this.id == 'purple') { $('body').css('background-color', 'purple') };
});
</pre>
</div>
<p>That will get our background changing color, but as soon as the page refreshes we&#8217;ll lose our changes. So let&#8217;s get rails involved.</p>
<h3 class="vag_post_header">2. Set up the appropriate models and associations</h3>
<p>I&#8217;ll move pretty quickly here cause it&#8217;s so easy. I assume you have a current_user stored in your session. I&#8217;ll also assume you&#8217;ve set up a one-to-one association between &#8216;users&#8217; and &#8216;profile_settings.&#8217; This means you should be able to do something like this in your controller:</p>
<div class="code_block">
<pre class="brush: ruby;">def make_background_green
	current_user.profile_setting.update_attributes(:background_color =&gt; 'green')
end
</pre>
</div>
<p>And then you can apply this color using inline style:</p>
<div class="code_block">
<pre class="brush: ruby;">
&lt;body style="background-color=&lt;%= current_user.profile_setting.background_color %&gt;;" &gt;
<div id="green" class="change_bg_color">&lt;%= link_to "Make Green", :action =&gt; "make_background_green" %&gt;</div>
<div id="yellow" class="change_bg_color">&lt;%= link_to "Make Yellow", :action =&gt; "make_background_yellow" %&gt;</div>
<div id="purple" class="change_bg_color">&lt;%= link_to "Make Purple", :action =&gt; "make_background_purple" %&gt;</div>

&lt;/body&gt;
</pre>
</div>
<p>Of course this is just nasty for a couple of reasons: (a) you&#8217;d have to write a new method for each possible color, (b) the markup is sort of ugly, and (c) we&#8217;re relying on a page refresh to do the work. So let&#8217;s clean this up a bit using AJAX.</p>
<h3 class="vag_post_header">3. Update your profile settings via AJAX.</h3>
<p>First, let&#8217;s get our html looking better:</p>
<div class="code_block">
<pre class="brush: html;">
&lt;body style="background-color=&lt;%= current_user.profile_setting.background_color %&gt;;" &gt;
<div id="green" class="change_bg_color">Make Green</div>
<div id="yellow" class="change_bg_color">Make Yellow</div>
<div id="purple" class="change_bg_color">Make Purple</div>

&lt;/body&gt;
</pre>
</div>
<p>Then lets add some AJAX to our click event:</p>
<div class="code_block">
<pre class="brush: jscript;">$('h3').click(function() {
	if (this.id == 'green') { $('body').css('background-color', 'green') };
	if (this.id == 'yellow') { $('body').css('background-color', 'yellow') };
	if (this.id == 'purple') { $('body').css('background-color', 'purple') };		

	$.post('http://your_site.com/profile_controller/change_background_color', {
		'background_color' : this.id
	});
});</pre>
</div>
<p>Here&#8217;s where you need to pay attention. We&#8217;re sending an AJAX post request with two arguments: (1) the url we&#8217;d like to load and (2) the data we&#8217;d like to pass along as a key/value pair. This means your controller is going to fire the &#8216;change_background_color&#8217; action and will have access to the params[:background_color] with a value equal to the clicked element&#8217;s id.</p>
<p>And so your controller will look like this:</p>
<div class="code_block">
<pre class="brush: ruby;">
def change_background_color
  current_user.profile_setting.update_attributes(:background_color =&gt; params[:background_color])
  render :nothing =&gt; true  # make sure the action knows not to load a template
end
</pre>
</div>
<h3 class="vag_post_header">4. Mission accomplished.</h3>
<p>Your profile settings should now be updating quietly in the background. If you have any problems, start up firebug and watch your AJAX hit register in the console log. This can be very helpful when debugging. But don&#8217;t get discouraged. Once you get this process down, all sorts of cool things become possible.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/making-jquery-and-rails-play-nice-with-ajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to make iterator methods in Ruby.</title>
		<link>http://coryschires.com/how-to-make-iterator-methods-in-ruby/</link>
		<comments>http://coryschires.com/how-to-make-iterator-methods-in-ruby/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 23:14:42 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=117</guid>
		<description><![CDATA[Most of us strictly rails developers don’t know how to make iterator methods or internal iterators. For example...]]></description>
			<content:encoded><![CDATA[<p>Most of us strictly rails developers don&#8217;t know how to make iterator methods (i.e. methods that accept blocks). For example, say you wanted to make a method to reverse each word in a string &#8211; not the entire string but each individual word. You could write this method:</p>
<div class="code_block">
<pre class="brush: ruby;">
class String
  def reverse_each_word
    self.split.collect { |word| word.reverse }
  end
end
</pre>
</div>
<div class="clear"></div>
<p>That works but suppose you wanted to abstract this logic to use elsewhere. So instead let&#8217;s write a method to iterate through each word in the sentence, yielding the result to a block. Then you can do whatever you want to each word (upcase, reverse, length, capitalize, etc). Now that&#8217;s a bit trickier: </p>
<div class="code_block">
<pre class="brush: ruby;">
class String
  def each_word
    self.split.each { |word| yield word }
  end
end
</pre>
</div>
<div class="clear"></div>
<p>And now you have a more flexible method which can do things like this:</p>
<div class="code_block">
<pre class="brush: ruby;">
"This is a very short sample string".each_word do |word|
  word.reverse.upcase
end
</pre>
</div>
<div class="clear"></div>
<p>Neat. But what&#8217;s going on here? The <span class="code_text">reverse_each_word</span> method is pretty vanilla &#8211; take a string, split the words into an array, reverse them, and return the collection. The <span class="code_text">each_word</span> method, however, is less straight forward. It starts out much the same &#8211; take a string, split the words into an array but then&#8230; </p>
<p>Well, it&#8217;s actually pretty simple. We use the keyword yield to let ruby know that our method is going to accept a block. And, more specifically, we&#8217;re telling ruby we&#8217;d like each word in our array to be yielded as parameters within that block. Now we can iterate through through each of our words &#8211; manipulating them however we please.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/how-to-make-iterator-methods-in-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

