
<?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-on-Rails</title>
	<atom:link href="http://coryschires.com/tag/ruby-on-rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://coryschires.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Tue, 14 Feb 2012 22:45:46 +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>Ten tips for writing better Cucumber steps</title>
		<link>http://coryschires.com/ten-tips-for-writing-better-cucumber-steps/</link>
		<comments>http://coryschires.com/ten-tips-for-writing-better-cucumber-steps/#comments</comments>
		<pubDate>Sun, 01 Jan 2012 23:08:19 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Best-Practices]]></category>
		<category><![CDATA[Capybara]]></category>
		<category><![CDATA[Cucumber]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=420</guid>
		<description><![CDATA[I've written hundreds of Cucumber steps. Here's some tips I learned along the way.]]></description>
			<content:encoded><![CDATA[<h3>1. Use flexible pluralization.</h3>
<p>Add a <span class="code_text">?</span> immediately following the pluralized word:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^the users? should receive an email$/ do
          # ...
        end
    </pre>
</div>
<p>The <span class="code_text">?</span> specifies that your looking for zero or more of the proceeding character. So the above example will capture both <span class="code_text">user</span> and <span class="code_text">users</span>.</p>
<h3>2. Use non-capturing groups to help steps read naturally.</h3>
<p>You can create non-capturing groups by adding a <span class="code_text">?:</span> to the beginning of a otherwise normal group (e.g. <span class="code_text">(?:some text)</span> rather than <span class="code_text">(some text)</span>). This is treated exactly like a normal group except that the result will is not captured and thus not passed as an argument to your step definition. This often useful in conjunction with alternation:</p>
<div class="code_block">
<pre class="brush: ruby;">
        And /^once the files? (?:have|has) finished processing$/ do
          # ...
        end
    </pre>
</div>
<p>Or another pattern I use regularly:</p>
<div class="code_block">
<pre class="brush: ruby;">
        When /^(?:I|they) create a profile$/ do
          # ...
        end
    </pre>
</div>
<h3>3. Consolidate step definitions by capturing optional groups.</h3>
<p>Often I find myself writing essentially the same step with both positive and negative assertions. You can remove this duplication by capturing an optional group:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^I should( not)? see the following columns: "([^"]*)"$/ do |negate, columns|
          within('table thead tr') do
            columns.split(', ').each do |column|
              negate ? page.should_not(have_content(column)) : page.should(have_content(column))
            end
          end
        end
    </pre>
</div>
<p>Here we&#8217;re capturing an optional group (note <span class="code_text">( not)?</span> using the <span class="code_text">?</span> mentioned above). We then pass that into our step as the <span class="code_text">negate</span> variable which we can use to write conditional assertions.</p>
<h3>4. Not all matched phrases need to be surrounded by quotes.</h3>
<p>Don&#8217;t assume that matched phrases must (or should) be enclosed in double quotes. Often quotes are a good idea. They make it visually clear which phrases will be passed to the step definition. For example:</p>
<div class="code_block">
<pre class="brush: plain;">
        Given I have "potatoes" in my cart
    </pre>
</div>
<p>That&#8217;s reasonable. The quotes highlight the parts that change without hurting readability. But sometimes, quotes are just poor style:</p>
<div class="code_block">
<pre class="brush: plain;">
        Given I have "7" items in my cart
    </pre>
</div>
<p>It should be pretty obvious that the number is variable. The quotes add nothing except noise. A better step would read:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^I have (\d+) items? in my cart$/ do |item_count|
          item_count.to_i.times { ... }
        end
    </pre>
</div>
<h3>5. Use transforms to make smarter, DRYer regular expressions.</h3>
<p>There&#8217;s an opportunity to refactor the previous example. Do you see it? Cucumber passes everything as a string, so you must remember to convert types within your step definition (e.g. above we use <span class="code_text">to_i</span> to transform <span class="code_text">item_count</span> into a proper integer). That&#8217;s annoying and easy to forget.</p>
<p>Fortunately, Cucumber gives us a way to avoid this peskiness by using <span class="code_text">Transform</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        CAPTURE_A_NUMBER = Transform /^\d+$/ do |number|
          number.to_i
        end
    </pre>
</div>
<p>And we can use this in our steps:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^I have (#{CAPTURE_A_NUMBER}) items? in my cart$/ do |item_count|
          item_count.times { ... }
        end
    </pre>
</div>
<p>Not only have we removed the need to call <span class="code_text">to_i</span> but we&#8217;ve also moved our regex into a reusable constant.</p>
<h3>6. Define methods to DRY up your step definitions.</h3>
<p>Sometimes it&#8217;s a good idea to remove duplication by defining methods. For example, it&#8217;s common to define a <span class="code_text">current_user</span> method:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def current_user
          User.find_by_email('current_user@example.com')
        end
    </pre>
</div>
<p>Similarly, if you find yourself wrapping several steps with the same logic, you might consider making a helper method. On <a href="http://scholasticahq.com/">Scholastica</a>, we test a lot of lightboxes using of this method:</p>
<div class="code_block">
<pre class="brush: ruby;">
        def within_lightbox(opts = {sleep: 0} )
          sleep(opts[:sleep])
          within_frame("prettyPhotoIframe") { yield }
        end
    </pre>
</div>
<p>And our step definitions stay nice and clean:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^some stuff should be visible in the lightbox$/ do
          within_lightbox { page.should have_content('Some Stuff') }
        end
    </pre>
</div>
<p>By convention, these methods should live in <span class="code_text">features/support/world_extensions.rb</span> and be included in the Cucumber <span class="code_text">World</span> module. But keep in mind this is a tradeoff: you&#8217;re removing duplication but adding indirection. You should be reluctant to define methods until the code makes it very obvious that it&#8217;s a good idea.</p>
<h3>7. Use steps within steps.</h3>
<p>Sometimes it&#8217;s useful to call steps within steps. Another example from <a href="scholasticahq.com">Scholastica</a>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        When /^the request for an expedited decision should be canceled$/ do
          manuscript.should_not be_expedited
          step %{"#{current_user.email}" should receive an email with subject "Expedited decision request canceled"}
        end
    </pre>
</div>
<p>But don&#8217;t go crazy, it&#8217;s better to use the capybara methods directly when possible:</p>
<div class="code_block">
<pre class="brush: ruby;">
        When /^I update the email template to read "([^"]*)"$/ do |text|
          fill_in("email_template[text], with: text)
          click_button("Save changes and close")
          # Rather than...
          # step %{I fill in "email_template[text]" with "#{text}"}
          # step %{I press "Save changes and close"}
        end
    </pre>
</div>
<h3>8. Improve readability with unanchored regular expressions.</h3>
<p>Most step definitions look something like:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Given /^I am an admin user$/ do |item_count|
          # ...
        end
    </pre>
</div>
<p>Note we&#8217;re using <span class="code_text">^</span> and <span class="code_text">$</span> to anchor our regex to the start and end of the captured string. This ensures the regular expression exactly matches &#8220;I am an admin user&#8221; (i.e. allows no additional words at the beginning or end of the step). Most of the time, this is exactly what want.</p>
<p>Occasionally, however, it makes sense to omit the final <span class="code_text">$</span>. Take this step for example:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Then /^wait (\d+) seconds/ do |seconds|
          sleep(seconds.to_i)
        end
    </pre>
</div>
<p>Now you can use this definition to write flexible, expressive steps:</p>
<div class="code_block">
<pre class="brush: plain;">
        Then wait 2 seconds for the revenue statistics to finish loading
        Then wait 5 seconds while the document is converted
    </pre>
</div>
<h3>9. When your steps must include data, use tables.</h3>
<p>Generally, steps should be human readable and that means they shouldn&#8217;t include loads of cryptic data. But sometimes, you have no other choice. In those cases, use tables to clearly represent the data:</p>
<div class="code_block">
<pre class="brush: plain;">
        Given "Frankie's Hams" are selling for $25:
        And the following orders have been placed:
          | buyer email      | quantity |
          | eddy@example.com | 3        |
          | matt@example.com | 2        |
    </pre>
</div>
<p>Using tables within your step definitions can get a bit tricky. I use <a href="https://gist.github.com/1548498">this helper method</a> but you should really <a href="https://github.com/cucumber/cucumber/blob/master/lib/cucumber/ast/table.rb">read the relevant source code</a> and figure out what makes sense for your application.</p>
<h3>10. Don&#8217;t get carried away and spoil a good thing.</h3>
<p>As you use these tips, remember that tests should favor clarity over cleverness. In other words, if you&#8217;re removing a small amount of duplication but adding a lot of complexity, that&#8217;s a poor tradeoff. Here&#8217;s an example from <a href="scholasticahq.com">Scholastica</a>:</p>
<div class="code_block">
<pre class="brush: ruby;">
        Given /^(?:I|they) have opened (?:a|an) ([^\s]+) invitation$/ do |invitation_type|
          invitation = Factory("#{invitation_type}_invitation".to_sym, recipient: current_user, to: current_user.email)
          reset_mailer
          eval "ApplicationMailer.invite_#{invitation_type}(invitation).deliver"
          open_email(current_user.email)
        end
    </pre>
</div>
<p>This steps allows us to write both <span class="code_text">Given I have opened a reviewer invitation</span> and <span class="code_text">Given I have opened an editor invitation</span>. I&#8217;d say this step is borderline too complex (lots of interpolation and an eval). Maybe it would be better to just write two separate steps? Remember no one is testing your tests so don&#8217;t fuck around. A little bit of duplication is not the end of the world.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/ten-tips-for-writing-better-cucumber-steps/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Adding default configuration options to Paperclip</title>
		<link>http://coryschires.com/add-default-configuration-options-to-paperclip/</link>
		<comments>http://coryschires.com/add-default-configuration-options-to-paperclip/#comments</comments>
		<pubDate>Sun, 24 Jul 2011 00:02:40 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[paperclip]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=408</guid>
		<description><![CDATA[DRY up your paperclip'd models by making a paperclip_defaults initializer.]]></description>
			<content:encoded><![CDATA[<p>Using paperclip, you&#8217;ll often put something like this in your models:</p>
<div class="code_block">
<pre class="brush: ruby;">
      has_attached_file :article_text,
        :storage => :s3,
        :s3_credentials => {
          :bucket => ENV['AS3_BUCKET'],
          :access_key_id => ENV['AS3_ACCESS_KEY_ID'],
          :secret_access_key => ENV['AS3_SECRET_ACCESS_KEY']
        }
       :s3_permissions => :private,
       :processors => [:manuscript_converter],
       :path => "manuscript/:id/:uploaded_manuscript_filename"
    </pre>
</div>
<p>Many of these settings will be repeated in every paperclip&#8217;d model. You can easily remove that duplication by adding an initializer. In <span class="code_text">config/initializers/paperclip_defaults.rb</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
      Paperclip::Attachment.default_options.merge!(
        :storage => :s3,
        :s3_credentials => {
          :bucket => ENV['AS3_BUCKET'],
          :access_key_id => ENV['AS3_ACCESS_KEY_ID'],
          :secret_access_key => ENV['AS3_SECRET_ACCESS_KEY']
        }
      )
    </pre>
</div>
<p>And now you can remove those options from all your models – separating the parts that change from the parts that stay the same.</p>
<p>I had trouble finding this online and had to dig through the source code to figure it out. So maybe it will help someone else save a little time.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/add-default-configuration-options-to-paperclip/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>How to equip rails for behavior driven development.</title>
		<link>http://coryschires.com/how-to-equip-rails-for-behavior-driven-development/</link>
		<comments>http://coryschires.com/how-to-equip-rails-for-behavior-driven-development/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 01:29:33 +0000</pubDate>
		<dc:creator>Cory Schires</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Cucumber]]></category>
		<category><![CDATA[RSpec]]></category>
		<category><![CDATA[Ruby-on-Rails]]></category>
		<category><![CDATA[Selenium]]></category>

		<guid isPermaLink="false">http://coryschires.com/?p=214</guid>
		<description><![CDATA[There's a lot of hype around behavior driven development. Learn how to get your application equipped for the challenge...]]></description>
			<content:encoded><![CDATA[<p>First, you&#8217;re going to need a few gems: cucumber, rspec-rails, rspec, and webrat. Although there are a number of ways you can get these running in your new rails project, the best plan is to set up gem dependencies directly in your application using the handy <span class="code_text">config.gem</span> command. </p>
<p>Just add these lines to <span class="code_text">config/environments/test.rb</span>:</p>
<div class="code_block">
<pre class="brush: ruby;">
		config.gem 'rspec-rails' , :lib => false
		config.gem 'rspec' , :lib => false
		config.gem 'cucumber'
		config.gem 'webrat'
	</pre>
</div>
<p>Next, make sure these gems are installed by typing:</p>
<div class="code_block">
<pre class="brush: plain;">
		RAILS_ENV=test sudo rake gems:install
	</pre>
</div>
<p>Finally, you&#8217;ll need to bootstrap your rails application for development with Cucumber and RSpec. Simply type:</p>
<div class="code_block">
<pre class="brush: plain;">
		script/generate rspec
		script/generate cucumber
	</pre>
</div>
<p>That&#8217;s it. Now you&#8217;re set up for behavior driven development in your rails app.</p>
]]></content:encoded>
			<wfw:commentRss>http://coryschires.com/how-to-equip-rails-for-behavior-driven-development/feed/</wfw:commentRss>
		<slash:comments>1</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>

