<?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"
	>

<channel>
	<title>Glenn Fu</title>
	<atom:link href="http://www.glennfu.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.glennfu.com</link>
	<description>code like water, compile like bamboo!</description>
	<pubDate>Tue, 26 Aug 2008 23:02:02 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6</generator>
	<language>en</language>
			<item>
		<title>Mock Expectation Fails on Associated Model (Association Proxy)</title>
		<link>http://www.glennfu.com/2008/07/01/mock-expectation-fails-on-associated-model-association-proxy/</link>
		<comments>http://www.glennfu.com/2008/07/01/mock-expectation-fails-on-associated-model-association-proxy/#comments</comments>
		<pubDate>Tue, 01 Jul 2008 20:35:47 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[association proxy]]></category>

		<category><![CDATA[ruby on rails]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/?p=37</guid>
		<description><![CDATA[I just hit a real mean snag today trying to put an expectation on a model and it didn&#8217;t get caught like it should.  This is something I do all the time so I knew I wasn&#8217;t just making a basic typo.  Here&#8217;s what my setup looked like:
The model

def purchase
  send_shipping_notice
end

def send_shipping_notice
 [...]]]></description>
			<content:encoded><![CDATA[<p>I just hit a real mean snag today trying to put an expectation on a model and it didn&#8217;t get caught like it should.  This is something I do all the time so I knew I wasn&#8217;t just making a basic typo.  Here&#8217;s what my setup looked like:</p>
<p>The model</p>
<pre>
def purchase
  send_shipping_notice
end

def send_shipping_notice
  puts "hi"
end
</pre>
<p>In my spec/test</p>
<pre>
def given_bought_on(date)
  wp = @order.product
  puts wp.inspect
  wp.should_receive(:send_shipping_notice)
  wp.purchase
end
</pre>
<p>The output</p>
<pre>
#&lt;Product id: 270, owner_id: 270, name: 'thing'&gt;
hi

1)
Spec::Mocks::MockExpectationError in 'Product should purchase'
Mock 'Product' expected :send_shipping_notice with (any args) once, but received it 0 times
./spec/models/product_spec.rb:21:in `given_bought_on'
script/spec:4:
</pre>
<p>So as you can see, I put an expectation on the <code>wp</code> variable, and verify it gets called by seeing &#8216;Hi&#8217; get printed.  However the expectation totally gets overlooked and my test framework complains that it never happened.</p>
<p>The catch is that the <code>wp</code> in my test and the web_page <code>self</code> inside the model are two different models.  So the expectation is on a different model.  Calling <code>.object_id</code> or <code>.inspect</code> on either one will affirm (or rather lie) to you that they&#8217;re the same, but they are not.</p>
<p>This is (as I&#8217;m told) well documented in ActiveRecord and is intentional by design.  The <code>wp</code> variable is in fact an Association Proxy, not the WebPage I think it is.  It just lies to you outright so you think it&#8217;s a WebPage.</p>
<p>My solution, while rather a hack, is the only thing I know to get my spec to pass:</p>
<pre>
def given_bought_on(date)
  <strong>wp = Product.find(@order.product_id)</strong>
  puts wp.inspect
  wp.should_receive(:send_shipping_notice)
  wp.purchase
  <strong>@order.reload</strong>
end
</pre>
<p>Now it grabs the model directly and there&#8217;s no confusion.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/07/01/mock-expectation-fails-on-associated-model-association-proxy/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Rails Pagination by Letters (not Numbers like will_paginate)</title>
		<link>http://www.glennfu.com/2008/06/24/rails-pagination-by-letters-not-numbers-like-will_paginate/</link>
		<comments>http://www.glennfu.com/2008/06/24/rails-pagination-by-letters-not-numbers-like-will_paginate/#comments</comments>
		<pubDate>Tue, 24 Jun 2008 20:00:42 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[pagination]]></category>

		<category><![CDATA[ruby on rails]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/?p=36</guid>
		<description><![CDATA[I want my list of data to be paginated by letters.  The will_paginate plugin certainly gives excellent pagination if all you want is &#8220;prev 1 2 3 .. 6 next&#8221; kind of pagination.
However what if you&#8217;re looking for entries that start with the letter H and you have no idea if that&#8217;s page 4 [...]]]></description>
			<content:encoded><![CDATA[<p>I want my list of data to be paginated by letters.  The <a href="http://github.com/mislav/will_paginate/wikis">will_paginate</a> plugin certainly gives excellent pagination if all you want is &#8220;prev 1 2 3 .. 6 next&#8221; kind of pagination.</p>
<p>However what if you&#8217;re looking for entries that start with the letter H and you have no idea if that&#8217;s page 4 or page 42?  You&#8217;re probably wanting something more like &#8220;# A B C D&#8230;&#8221; pagination.</p>
<p>I did some googling and found people speaking of solutions for &#8220;A B C D&#8230;&#8221; but in my case, not all of my entries start with letters!  If you have something like media titles in your data set, having an entry start with a number is perfectly normal.  Some might even start with special characters!  Some people suggest having an &#8216;All&#8217; option, but if you need pagination, it&#8217;s probably because you have enough data that showing all options at once is a very bad idea.</p>
<p>Here&#8217;s my solution:</p>
<p>First I make a helper function for my options that&#8217;ll be cached permanently.</p>
<pre>
def letter_options
  $letter_options_list ||= ['#'].concat(("A".."Z").to_a)
end
</pre>
<p>Here&#8217;s my index action in my controller:</p>
<pre>
@letter = params[:letter].blank? ? 'a' : params[:letter]
if params[:letter] == '#'
  @data = Model.find(:all, :conditions => ["title REGEXP ?",
      "^[^a-z]"], :order => 'title', :select => "id, title")
else
  @data = Model.find(:all, :conditions => ["title LIKE ?",
      "#{params[:letter]}%"], :order => 'title', :select => "id, title")
end
</pre>
<p>Here&#8217;s my html</p>
<pre>
&lt;div class ="pagination"&gt;
  &lt;% letter_options.each do |letter| %&gt;
    &lt;% if params[:letter] == letter %&gt;
      &lt;span class="current"&gt;&lt;%= letter %&gt;&lt;/span&gt;
    &lt;% else %&gt;
      &lt;%= link_to letter, staff_games_path(:letter =&gt; letter)%&gt;
    &lt;% end %&gt;
  &lt;% end %&gt;
&lt;/div&gt;
</pre>
<p>There we go!  Now the # will pull up all entries where the first character is not a letter.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/06/24/rails-pagination-by-letters-not-numbers-like-will_paginate/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Attachment Fu and Zip Files - RubyZip and Extracting For Bulk Uploads</title>
		<link>http://www.glennfu.com/2008/06/19/attachment-fu-and-zip-files-rubyzip-and-extracting-for-bulk-uploads/</link>
		<comments>http://www.glennfu.com/2008/06/19/attachment-fu-and-zip-files-rubyzip-and-extracting-for-bulk-uploads/#comments</comments>
		<pubDate>Fri, 20 Jun 2008 03:03:13 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[attachment fu]]></category>

		<category><![CDATA[mime types]]></category>

		<category><![CDATA[rubyzip]]></category>

		<category><![CDATA[zip]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/?p=35</guid>
		<description><![CDATA[Today I&#8217;m going to share how you can let your app accept zip files which will then be extracted into multiple attachments.  If you already use Attachment Fu to manage files, this should be super easy to add.
Before my controller had something like this:

Attachment.create(:uploaded_data => params[:Filedata])

First break that up into something more like this:

attachment [...]]]></description>
			<content:encoded><![CDATA[<p>Today I&#8217;m going to share how you can let your app accept zip files which will then be extracted into multiple attachments.  If you already use <a href="http://agilewebdevelopment.com/plugins/attachment_fu">Attachment Fu</a> to manage files, this should be super easy to add.</p>
<p>Before my controller had something like this:</p>
<pre>
Attachment.create(:uploaded_data => params[:Filedata])
</pre>
<p>First break that up into something more like this:</p>
<pre>
attachment = Attachment.new
attachment.uploaded_data = params[:Filedata]
attachment.save
</pre>
<p>Then put in some split logic for if it&#8217;s a zip file:</p>
<pre>
attachment = Attachment.new
attachment.uploaded_data = params[:Filedata]

if attachment.content_type == "application/zip"
    # Unzip this and process all the inner files
    Attachment.build_from_zip(attachment)
else
    attachment.save
end
</pre>
<p>Now we&#8217;ll need the <a href="http://sourceforge.net/projects/rubyzip">RubyZip</a> gem and <a href="http://mime-types.rubyforge.org/">MIME Types</a> gem, so do:</p>
<pre>
sudo gem install rubyzip
sudo gem install mime-types
</pre>
<p>Now in the <code>Attachment</code> class we&#8217;ll add the <code>build_from_zip</code> method:</p>
<pre>
def self.build_from_zip(ss)
 zipfile = Zip::ZipFile.open(ss.temp_path)

 zipfile.each do |entry|
   if entry.directory?
     next
   elsif entry.name.include?("/")
     next
   else
     screen = Attachment.new
     screen.filename = entry.name
     screen.temp_data = zipfile.read(entry.name)

     mime = MIME::Types.type_for(entry.name)[0]
     screen.content_type = mime.content_type unless mime.blank?

     screen.save
   end
 end

end
</pre>
<p>The only two non-obvious things to note here are:</p>
<ul>
<li>I skip the files with / in them because when I archive files on my machine, hidden files with / characters in them make it into the archive.  I only want the real files.</li>
<li>I use the MIME Types gem to decide the content type from the filename.</li>
</ul>
<p>I hope you find this helpful, enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/06/19/attachment-fu-and-zip-files-rubyzip-and-extracting-for-bulk-uploads/feed/</wfw:commentRss>
		</item>
		<item>
		<title>IE6 vs JavaScript (Prototype) and Sortable Elements Hidden/Disappearing/Invisible</title>
		<link>http://www.glennfu.com/2008/05/23/ie6-vs-javascript-prototype-and-sortable-elements-hiddendisappearinginvisible/</link>
		<comments>http://www.glennfu.com/2008/05/23/ie6-vs-javascript-prototype-and-sortable-elements-hiddendisappearinginvisible/#comments</comments>
		<pubDate>Fri, 23 May 2008 22:33:50 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[ajax]]></category>

		<category><![CDATA[javascript]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/?p=34</guid>
		<description><![CDATA[Today I have another IE6 quirk in dealing with Prototype.  I have a bunch of elements that I want to sort with a Sortable object, which works as expected for the most part, except in IE6!
I set background-color: #E6F2FF; to the rows of my &#8216;table&#8217; which of course isn&#8217;t a real table, just some [...]]]></description>
			<content:encoded><![CDATA[<p>Today I have another IE6 quirk in dealing with Prototype.  I have a bunch of elements that I want to sort with a <code>Sortable</code> object, which works as expected for the most part, except in IE6!</p>
<p>I set <code>background-color: #E6F2FF;</code> to the rows of my &#8216;table&#8217; which of course isn&#8217;t a real table, just some nicely styled div&#8217;s!  The problem with this is that there&#8217;s a bug in this situation with IE6.  All the contents of my rows are hidden!  That means text, links, images.  It looks as if all of the rows are just empty&#8230; except I can mouse-over and my mouse can interact with the elements.</p>
<p>It turns out, the <code>opacity</code> css attribute is 0.  Or at least IE6 behaves as if it is.  The thing is, FireBug doesn&#8217;t agree, and if you set <code>opacity: 1;</code> in your stylesheet it won&#8217;t cut it.  The problem begins just after the <code>Sortable.Create</code> call.  Removing this call fixes the problem, obviously, but that&#8217;s not what we want!</p>
<p>Here&#8217;s my solution.  After the <code>Sortable.Create</code> call, do this:</p>
<pre>
if (Prototype.Browser.IE) {
    $$('.relevant_class_name').invoke.setStyle({opacity: 1});
}
</pre>
<p>where <code>relevant_class_name</code> is the css class assigned to the row&#8217;s of data on my page.  This sets the opacity to all of the affected elements after the the <code>Sortable</code> object screws things up.</p>
<p>Hooray!  I hope this helps someone else.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/05/23/ie6-vs-javascript-prototype-and-sortable-elements-hiddendisappearinginvisible/feed/</wfw:commentRss>
		</item>
		<item>
		<title>IE vs JavaScript (Prototype) and position: relative</title>
		<link>http://www.glennfu.com/2008/04/04/ie-vs-javascript-prototype-and-position-relative/</link>
		<comments>http://www.glennfu.com/2008/04/04/ie-vs-javascript-prototype-and-position-relative/#comments</comments>
		<pubDate>Fri, 04 Apr 2008 20:55:10 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[ajax]]></category>

		<category><![CDATA[javascript]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/?p=23</guid>
		<description><![CDATA[In the current project I&#8217;m working on I have all sorts of cool AJAX madness happening to add things to my pages.  For one particular example, I have AJAX calls that add pieces to the page with more AJAX functions inside of those pieces.  Fun, huh?
The kicker is that some of the elements [...]]]></description>
			<content:encoded><![CDATA[<p>In the current project I&#8217;m working on I have all sorts of cool AJAX madness happening to add things to my pages.  For one particular example, I have AJAX calls that add pieces to the page with more AJAX functions inside of those pieces.  Fun, huh?</p>
<p>The kicker is that some of the elements on the page there are being shown with the style attribute of <code>position: static;</code>.  It just so happens that Prototype and <code>position: static</code> do not always play nicely in this case.</p>
<p>Let me show you what I mean.  Here you see an image with two links placed with <code>position: static;</code>.<br />
<img src="http://www.glennfu.com/wp-content/uploads/2008/04/picture-15.png" alt="" title="picture-15" width="500" height="277" class="alignleft size-full wp-image-24" /></p>
<p>Clicking on &#8220;+ Add Foo&#8221; twice and &#8220;+ Change Bar&#8221; gives:<br />
<img src="http://www.glennfu.com/wp-content/uploads/2008/04/picture-20.png" alt="" title="picture-20" width="500" height="383" class="alignleft size-full wp-image-29" /></p>
<p>This works as expected.  However if I add a duplication of this segment of the page using an AJAX call, the new portion does not work as expected while in Internet Explorer (every other browser works just fine of course).</p>
<p>To illustrate the problem while trying to do the same thing with the new segment, first I add the new segment via the &#8220;+ Add Many Things&#8221; link.<br />
<img src="http://www.glennfu.com/wp-content/uploads/2008/04/picture-21.png" alt="" title="picture-21" width="500" height="446" class="alignleft size-full wp-image-30" /></p>
<p>Then I click &#8220;- Change Bar&#8221; which hides the following two lines.  You now see the two links I&#8217;ve been referring do <strong>not</strong> follow the movement of the page.  They should have scrolled up and they did not.<br />
<img src="http://www.glennfu.com/wp-content/uploads/2008/04/picture-22.png" alt="" title="picture-22" width="500" height="408" class="alignleft size-full wp-image-31" /></p>
<p>To handle this, I need some extra JavaScript.  First I add the following to the parameters of my AJAX call:</p>
<pre>
onSuccess: function(request){ reposition(); }
</pre>
<p>Next I want to take the elements that I know I have this problem with (selected by class name) and then first turn off the &#8220;relative&#8221; position by setting it to &#8220;static&#8221; and then back to &#8220;relative&#8221; again.  By the way I figured this out thanks to way too much time fiddling with things in FireBug and the IE Dom Inspector.  I can&#8217;t come up with any real sense to it.  To make this happen, I add the following JavaScript for IE only:</p>
<pre>

function reposition() {
  if (Prototype.Browser.IE) {
     $('publication_list').select('.remove').each(swapStaticToRelative);
     $('publication_list').select('.add_company_role').each(swapStaticToRelative);
     $('publication_list').select('.add_cover').each(swapStaticToRelative);
  }
}
function swapStaticToRelative(item) {
	item.setStyle({ position: 'static' });
	item.setStyle({ position: 'relative' });
}
</pre>
<p>Note that the following also works for detecting that the browser is any version of IE:</p>
<pre>
function reposition() {
     /*@cc_on
          /*@if (@_win32)
               $('publication_list').select('.remove').each(swapStaticToRelative);
               $('publication_list').select('.add_company_role').each(swapStaticToRelative);
               $('publication_list').select('.add_cover').each(swapStaticToRelative);
          @else @*/

          /*@end
     @*/
}
</pre>
<p>I wish I could remember where I found that, but it&#8217;s crazy cool.  Sure the Prototype way is better&#8230; but this is a fun one to stare at for a while until you figure out how it&#8217;s working.</p>
<p>So with that change in place, this time it works as expected.<br />
<img src="http://www.glennfu.com/wp-content/uploads/2008/04/picture-23.png" alt="" title="picture-23" width="500" height="421" class="alignleft size-full wp-image-32" /></p>
<p>The only thing better I think (aside from IE not sucking) would be to have a way to select fields by style attributes.  If I could figure that out, I&#8217;d be able to make a single call to swap these CSS attributes for all instances on the page that are relevant to this problem.  If I could do that, then it might be a candidate for a patch to Prototype.</p>
<p>If you have a suggestion for a better way to handle this or if my post helped you out, please let me know by leaving a comment!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/04/04/ie-vs-javascript-prototype-and-position-relative/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Easy PlainText Stories in Ruby on Rails using WebRat</title>
		<link>http://www.glennfu.com/2008/03/31/easy-plaintext-stories-in-ruby-on-rails-using-webrat/</link>
		<comments>http://www.glennfu.com/2008/03/31/easy-plaintext-stories-in-ruby-on-rails-using-webrat/#comments</comments>
		<pubDate>Mon, 31 Mar 2008 16:02:54 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[plaintext]]></category>

		<category><![CDATA[ruby on rails]]></category>

		<category><![CDATA[stories]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<category><![CDATA[webrat]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/?p=21</guid>
		<description><![CDATA[Building off of my last post on Stories, I&#8217;d like to show you some improvements I was able to make with the help of WebRat.
You can install WebRat using:

script/plugin install http://svn.eastmedia.net/public/plugins/webrat/

I got the inspiration from Ben Mabey at &#8216;ben.send :blog&#8217; which illustrates an approach to stories that is unbelievably easy to pick up.  He [...]]]></description>
			<content:encoded><![CDATA[<p>Building off of my <a href="http://www.glennfu.com/2008/03/27/reuse-scenarios-with-givenscenario-in-rspec-storyrunner/">last post on Stories</a>, I&#8217;d like to show you some improvements I was able to make with the help of <a href="http://www.brynary.com/2007/12/8/webrat-0-1-0-released">WebRat</a>.</p>
<p>You can install WebRat using:</p>
<pre>
script/plugin install http://svn.eastmedia.net/public/plugins/webrat/
</pre>
<p>I got the inspiration from <a href="http://www.benmabey.com/2008/02/04/rspec-plain-text-stories-webrat-chunky-bacon/">Ben Mabey at &#8216;ben.send :blog&#8217;</a> which illustrates an approach to stories that is unbelievably easy to pick up.  He also provides source code to the example that he&#8217;s built so that you can play with it.  Very cool!</p>
<p>I snagged that source myself and started playing with it, and added a lot of functionality of my own that I found useful.  The real cool thing is that the ONLY application specific code I have is this:</p>
<pre>
# user_steps.rb
steps_for(:user) do

  Given("that $actor is not logged in") do |actor|
    get "/sessions/destroy"
    response.should be_redirect
    flash[:notice].should == "You have been logged out."

    #fails here even though in the next request it will pass
    #controller.should_not be_logged_in
  end

  Then("$actor $should be logged in") do |actor, should|
    controller.send(shouldify(should), be_logged_in)
  end

end

# navigation_steps.rb
def path_from_descriptive_name(page_name)
  case page_name
  when "home"
    ""
  when "signup"
    "users/new"
  when "login"
    "sessions/new"
  else
    "#{page_name}"
  end
end
</pre>
<p>With that, and the generic application-independent helper methods that also live in my steps directory, I can write the following story:</p>
<pre>
Story: Making posts

  As a visitor
  I want to be a member
  So that I can make posts

    Scenario: Glenn creates a new account
      Given that Glenn is not logged in
      And there are some number of users
      And no user with login 'Glenn' exists

      When he goes to the signup page
      And fills in Login with 'Glenn'
      And fills in Email with 'glenn@glennfu.com'
      And fills in Password with 'blah'
      And fills in Confirm Password with 'blah'
      And clicks the 'Sign up' button

      Then there should be 1 more user
      And a user with login 'Glenn' should exist

    Scenario: Glenn logs in
      GivenScenario Glenn creates a new account

      When Glenn goes to the login page
      And fills in Login with 'Glenn'
      And fills in Password with 'blah'

      Then he should be logged in

    Scenario: A member makes a post while logged in
      GivenScenario Glenn logs in
      And there are some number of posts

      When he goes to the posts page
      And clicks on 'New post'
      And fills in Title with 'Woo'
      And fills in body with 'Stuff here'
      And clicks the 'Create' button

      Then there should be 1 more post
      And a post with title 'Woo' should exist

    Scenario: A nice lady makes a post while not logged in
      Given that she is not logged in
      Then she should not be logged in

      Given there are some number of posts

      When she goes to the posts page
      And clicks on 'New post'

      Then she should see the login page

    Scenario: An angry visitor should be able to see posts
      Given that he is not logged in

      When he goes to the posts page

      Then he better not f'ing see the login page

    Scenario: A visitor should not be able to edit posts
      GivenScenario A member makes a post while logged in
      And that she is not logged in

      When she goes to the posts page
      And clicks on 'Edit'

      Then she should see the login page
</pre>
<p>Pretty cool, huh?  I was even able to add some personality with the angry visitor Scenario.  Notice that I don&#8217;t have any steps written about Posts or my PostsController.  I don&#8217;t need it because I have generic model steps that parse the model from the text in my PlainText instructions.  It has all the basics that you need.  You interact with forms and links on the top level by name, and then check the results either by text on the page or by finding models.</p>
<p>If you&#8217;d like to play with it yourself, I&#8217;ve zipped up <a href="http://www.glennfu.com/wp-content/uploads/2008/03/stories.zip">my stories folder</a> for you to play with.</p>
<p><a href="http://www.glennfu.com/wp-content/uploads/2008/03/stories.zip">Download it here!</a></p>
<p>It also has the old user_story.rb from the previous example.  If you have any suggestions for improvements to this or ideas for something else I should do with it, please leave a comment!</p>
<p>My only quirk with this is that if you check the first step in the <code>steps_for(:user)</code> above you&#8217;ll see I have a line commented out.  It checks for <code>controller.should_not be_logged_in</code> and if I uncomment it, the check fails even though the two above it pass.  As you can see in the PlainText, on the very next line I call the very same check and it passes.  If you could help me figure out my mistake here I&#8217;d really appreciate you leaving a comment with your thoughts!</p>
<p>I hope you find this useful, and if so, be sure to go toss a thank you over to <a href="http://www.benmabey.com/">Ben</a> for the inspiration.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/03/31/easy-plaintext-stories-in-ruby-on-rails-using-webrat/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Reuse Given Scenarios with GivenScenario in RSpec StoryRunner</title>
		<link>http://www.glennfu.com/2008/03/27/reuse-scenarios-with-givenscenario-in-rspec-storyrunner/</link>
		<comments>http://www.glennfu.com/2008/03/27/reuse-scenarios-with-givenscenario-in-rspec-storyrunner/#comments</comments>
		<pubDate>Thu, 27 Mar 2008 21:26:56 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[rspec]]></category>

		<category><![CDATA[stories]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/2008/03/27/reuse-scenarios-with-givenscenario-in-rspec-storyrunner/</guid>
		<description><![CDATA[Update: I&#8217;ve made some improvements upon this using WebRat that you can read all about here.
I&#8217;m having a great time with RSpec&#8217;s new StoryRunner, and wanted to share a bit of what you can do with it.  I learn very well from examples and I know many others do as well so I hope [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update: </strong>I&#8217;ve made some improvements upon this using WebRat that you can <a href="http://www.glennfu.com/2008/03/31/easy-plaintext-stories-in-ruby-on-rails-using-webrat/">read all about here</a>.</p>
<p>I&#8217;m having a great time with <a href="http://rspec.info">RSpec</a>&#8217;s new StoryRunner, and wanted to share a bit of what you can do with it.  I learn very well from examples and I know many others do as well so I hope that this provides as a useful resource for getting your ideas flowing on how to use StoryRunner for your own projects.</p>
<p>To start, I set up a simple project using the following</p>
<pre>
# Create the project
rails blog
cd blog

# Install Restful Authentication
script/plugin install http://svn.techno-weenie.net/projects/plugins/restful_authentication/
script/generate authenticated user sessions

# Create a Post model
script/generate scaffold post title:string body:text published:boolean
</pre>
<p>Now I have the essentials for a simple app to play with.  Of course you&#8217;ll also want to <a href="http://rspec.info/documentation/rails/install.html">install RSpec</a>.</p>
<p>Now to try out StoryRunner!  I&#8217;ll write a story to cover the login system.  No need to write Spec&#8217;s for it, it&#8217;s already well tested.  However in writing this story we get a reusable Scenario that will be nice to have later, as well as give us a nice starting point for stories.</p>
<pre>
require File.join(File.dirname(__FILE__), "helper")

Story "User Stuff", %{
  As a writer
  I want to be a member
  So that I can make posts
}, :type => RailsStory do

  Scenario "I log in as a new user" do

    Given("that I am not logged in") do
      delete "/sessions/destroy"
      controller.should_not be_logged_in

      @user_count = User.count
    end

    When("I create a new user", "Glenn") do |name|
      @user = User.create(:login => name,
            :email => "#{name}@glennfu.com", :password => name,
            :password_confirmation => name)
    end

    Then("there should be 1 more user stored") do
      User.count.should == @user_count + 1
    end

    When("I login as", "Glenn") do |name|
     post "/sessions/create", :login => name, :password => name
    end

    Then("I should be logged in") do
      controller.should be_logged_in
      response.should be_redirect
    end
  end
end
</pre>
<p>This should be pretty easy to follow.  I start by logging out, then creating a user and logging in with it.  This is runnable with <code>ruby stories/user_story.rb</code></p>
<p>Now that this is already written, we can easily add similar stories.  Notice that we don&#8217;t have to re-define our steps here:</p>
<pre>
Scenario "I log in with the wrong user/password" do

  Given "that I am not logged in"
  When "I create a new user", "Glenn"
  Then "there should be 1 more user stored"
  When "I login as", "JoeBob"

  Then "I should not be logged in" do
    controller.should_not be_logged_in
    response.should_not be_redirect
  end
end
</pre>
<p>Now I&#8217;ll write a story for our Posts.  Notice the usage of &#8220;GivenScenario&#8221;, very cool!</p>
<pre>
Scenario "Create a new post while logged in" do

  GivenScenario "I log in as a new user"

  Then "I should be able to make a post" do
    post "/posts/create", :post => {:title => "the title",
            :body => "The body!"}

    @post = Post.find_by_title("the title")

    flash[:notice].should == "Post was successfully created."
    @post.should_not be_nil
    response.should be_redirect
  end
end
</pre>
<p>What if I want to also test posts failing?  I&#8217;ll modify the previous step to be a bit more robust (and also more useful).</p>
<pre>
Then "I $should be able to make a post", "should" do |should|
  post "/posts/create", :post => {:title => "my title",
            :body => "The body!"}

  @post = Post.find_by_title("my title")

  if should == "should"
    flash[:notice].should == "Post was successfully created."
    @post.should_not be_nil
  else
    flash[:notice].should be_nil
    @post.should be_nil
  end
  response.should be_redirect
end
</pre>
<p>With this change, I can easily add a new Scenario to test when making posts should fail:</p>
<pre>
Scenario "Create a new post while not logged in" do
  Given "that I am not logged in"
  Then "I $should be able to make a post", "should not"
end
</pre>
<p>I hope you found this useful!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/03/27/reuse-scenarios-with-givenscenario-in-rspec-storyrunner/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Overriding Time.now to Control the Server Time</title>
		<link>http://www.glennfu.com/2008/02/28/overriding-timenow-to-control-the-server-time/</link>
		<comments>http://www.glennfu.com/2008/02/28/overriding-timenow-to-control-the-server-time/#comments</comments>
		<pubDate>Thu, 28 Feb 2008 20:05:59 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[rspec]]></category>

		<category><![CDATA[ruby on rails]]></category>

		<category><![CDATA[time]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<category><![CDATA[world domination]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/2008/02/28/overriding-timenow-to-control-the-server-time/</guid>
		<description><![CDATA[I just recently worked on a project in which I needed to modify what time the Ruby on Rails server thought it was.  I was able to change this very easily with the help of court3nay while on #rubyonrails.

def Time.now
  Time.parse("2010-02-30", nil)
end

With this I am able to change the server time whenever I [...]]]></description>
			<content:encoded><![CDATA[<p>I just recently worked on a project in which I needed to modify what time the Ruby on Rails server thought it was.  I was able to change this very easily with the help of <a href="http://www.caboo.se/">court3nay</a> while on #rubyonrails.</p>
<pre>
def Time.now
  Time.parse("2010-02-30", nil)
end
</pre>
<p>With this I am able to change the server time whenever I want!  The system was one in which user interface capabilities changed at different times of the month.  Obviously I didn&#8217;t want to wait 20 days to see something different!</p>
<p>I placed this code snippet in my <code>config/environments/development.rb</code> file so that everything in my application could access it, and it wouldn&#8217;t affect the test or production environments.  The only downside to this is that you have to restart the server in order to change the time.  Of course, in RoR this takes like 5 seconds so it was no big deal for me.</p>
<p>In my specs I used stuff like</p>
<pre>
date = "2008-01-01"
Time.stub!(:now).and_return(Time.parse(date))
</pre>
<p>which of course made it very easy to write effective specs that covered all of my functionality.  Thank you <a href="http://rspec.info/">RSpec</a>!</p>
<p>Voila, now you too can <strong>control time</strong>!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/02/28/overriding-timenow-to-control-the-server-time/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Persistent Instance Variables in Ruby on Rails</title>
		<link>http://www.glennfu.com/2008/02/20/persistent-instance-variables-in-ruby-on-rails/</link>
		<comments>http://www.glennfu.com/2008/02/20/persistent-instance-variables-in-ruby-on-rails/#comments</comments>
		<pubDate>Wed, 20 Feb 2008 20:58:11 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[instance variables]]></category>

		<category><![CDATA[ruby on rails]]></category>

		<category><![CDATA[scope]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/2008/02/20/persistent-instance-variables-in-ruby-on-rails/</guid>
		<description><![CDATA[I just recently built a rake task in my project where I wanted to loop through a list of Users, queue up some data for each one, then loop back through them again to process the data that had been queued.  I didn&#8217;t need the data to live for very long, but  I [...]]]></description>
			<content:encoded><![CDATA[<p>I just recently built a rake task in my project where I wanted to loop through a list of Users, queue up some data for each one, then loop back through them again to process the data that had been queued.  I didn&#8217;t need the data to live for very long, but  I needed it for 2 separate requests.</p>
<p>The problem with this is that in Ruby on Rails, instance variables are <strong>not</strong> persistent across requests.  This means their scope is limited to one usage of an object and the next time you call for that object, the variable is gone.</p>
<p>Unfortunately, the only solution I could imagine for my problem without persistent instance variables was to create a massive join table to connect my generated data between Users.  Not only would this have been a lot of work, it would have been a big waste considering the data would have only lived for about a minute as the rake task was executed.</p>
<p>I wanted to improve/increase the scope of instance variables, and so my solution was to take advantage of <a href="http://wiki.rubyonrails.org/rails/pages/UnderstandingVariableLifetimes">Class Variables</a>.</p>
<p>At the bottom of my User class, I now have the following:</p>
<pre>
  protected
    def late_employees
      @@late_employees ||= {}
      @@late_employees[self] ||= {}
      @@late_employees[self]
    end

    def late_team_members
      @@late_team_members ||= {}
      @@late_team_members[self] ||= {}
      @@late_team_members[self]
    end

    def clear_late_emails
      @@late_employees[self] = {}
      @@late_team_members[self] = {}
    end
</pre>
<p>As you can see, each element of the Class Variable hashes are referenced by the current instance.  So when I call u.late_employees, it&#8217;s always the same across requests until either I call u.clear_late_emails or the server dies.</p>
<p>To use them, just treat them like any normal instance method/variable.  Here is an example of how you can do that:</p>
<pre>
def employee_late(user, days)
  if user.manager == self
    late_team_members[user] = days
  else
    late_employees[user] = days
  end
end

def has_late_employees?
  !(late_employees.empty? and late_team_members.empty?)
end

def send_late_employee_emails
  if has_late_employees?
    EvaluationNotifier.deliver_late_employee_notification(self)
  end

  length = late_employees.length + late_team_members.length
  clear_late_emails

  length
end
</pre>
<p>Voila, instance variables that are persistent across requests!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/02/20/persistent-instance-variables-in-ruby-on-rails/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Deploying Ruby on Rails with Capistrano on DreamHost</title>
		<link>http://www.glennfu.com/2008/02/01/deploying-ruby-on-rails-with-capistrano-on-dreamhost/</link>
		<comments>http://www.glennfu.com/2008/02/01/deploying-ruby-on-rails-with-capistrano-on-dreamhost/#comments</comments>
		<pubDate>Fri, 01 Feb 2008 19:56:14 +0000</pubDate>
		<dc:creator>Glenn Ford</dc:creator>
		
		<category><![CDATA[Miscellaneous]]></category>

		<category><![CDATA[capistrano]]></category>

		<category><![CDATA[dreamhost]]></category>

		<category><![CDATA[ruby on rails]]></category>

		<category><![CDATA[subversion]]></category>

		<guid isPermaLink="false">http://www.glennfu.com/2008/02/01/deploying-ruby-on-rails-with-capistrano-on-dreamhost/</guid>
		<description><![CDATA[When I set up my latest application on DreamHost, I had a real pain of a time.  Most of the references I found for help were written in 2006 and referred to outdated commands.  Since top Google results for &#8220;dreamhost capistrano ruby on rails&#8221; are mostly no longer adequate, I hope to help [...]]]></description>
			<content:encoded><![CDATA[<p>When I set up my latest application on DreamHost, I had a real pain of a time.  Most of the references I found for help were written in 2006 and referred to outdated commands.  Since top Google results for &#8220;dreamhost capistrano ruby on rails&#8221; are mostly no longer adequate, I hope to help out anyone else who finds themselves in my shoes!</p>
<p>I first got good help from <a href="http://www.rubynoob.com/articles/2006/9/22/how-to-deploy-your-first-rails-app-to-dreamhost-using-capistrano-in-windows">this resource at Rubynoob</a> which references the <a href="http://wiki.dreamhost.com/index.php/Capistrano">Dreamhost Capistrano Wiki article</a>.</p>
<p>With those two links and a bit of help from me, you should be all set.  To make things quick, let me summarize the key points:</p>
<ul>
<li>Set up your app with Fast-CGI enabled</li>
<li>Set up your own RubyGems following <a href="http://wiki.dreamhost.com/RubyGems">this resource</a></li>
<li>Also check out <a href="http://wiki.dreamhost.com/Ruby_on_Rails">this resource</a> for general Ruby on Rails + DreamHost concerns</li>
<li>&#8220;cap &#8211;apply-to .&#8221; is now &#8220;capify&#8221;</li>
<li>Download my <a href="http://www.glennfu.com/wp-content/uploads/2008/02/deploy.rb">deploy.rb</a> file or read from it below for good explanation of what most of the items do.</li>
<li>Set up your processes as shown below</li>
<li>Make sure every file in your /script folder has the first line: #!/usr/bin/env ruby</li>
<li>Make sure every file looking like /public/dispatch* has the first line: #!/usr/bin/env ruby</li>
</ul>
<p>My <a href="http://www.glennfu.com/wp-content/uploads/2008/02/deploy.rb">deploy.rb</a> file:</p>
<pre>
# The host where people will access my site
set :application, "test.gamelizard.com"
set :user, "my dreamhost username set to access this project"
set :admin_login, "my admin login name"

set :repository, "http://#{user}@svn.gamelizard.com/rgamelizard/trunk"

# If you aren't deploying to /u/apps/#{application} on the target
# servers (which is the default), you can specify the actual location
# via the :deploy_to variable:
set :deploy_to, "/home/#{admin_login}/#{application}"

# My DreamHost-assigned server
set :domain, "#{admin_login}@ajax.dreamhost.com"
role :app, domain
role :web, domain
role :db,  domain, :primary => true

desc "Link shared files"
task :before_symlink do
  run "rm -drf #{release_path}/public/bin"
  run "ln -s #{shared_path}/bin #{release_path}/public/bin"
end

set :use_sudo, false
set :checkout, "export"

# I used the handy quick tool to set up an SVN repository on DreamHost and this is where it lives
set :svn, "/usr/bin/svn"
set :svn_user, 'my svn username'
set :svn_password, 'my svn password'
set :repository,
  Proc.new { "--username #{svn_user} " +
       "--password #{svn_password} " +
       "http://svn.gamelizard.com/rgamelizard/trunk/" }

desc "Restarting after deployment"
task :after_deploy, :roles => [:app, :db, :web] do
  run "touch #{deploy_to}/current/public/dispatch.fcgi" 

  run "sed 's/# ENV\\[/ENV\\[/g' #{deploy_to}/current/config/environment.rb > #{deploy_to}/current/config/environment.temp"
  run "mv #{deploy_to}/current/config/environment.temp #{deploy_to}/current/config/environment.rb"
end

desc "Restarting after rollback"
task :after_rollback, :roles => [:app, :db, :web] do
  run "touch #{deploy_to}/current/public/dispatch.fcgi"
end
</pre>
<p>My script/process/reaper file:</p>
<pre>
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/process/reaper'
</pre>
<p>My script/process/spawner file:</p>
<pre>
#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../../config/boot'
require 'commands/process/spawner'
</pre>
<p>The permissions in the script/process folder should look like:</p>
<pre>
-rwxr-xr-x  1 Malohkan  staff  108 Jan  7 19:06 reaper
-rwxr-xr-x  1 Malohkan  staff  109 Jan  7 19:06 spawner
</pre>
<p>If they look like &#8220;-rwxr-xr-x@&#8221; as can happen on a Mac you&#8217;ll want to kill the file and re-create it with the same content.  I <strong>think</strong> this happens due to copying files and is representative of the notion that only the current logged-in user can access that file.  As a result, when Capistrano deploys the file, it will not have permission to run it.</p>
<p>If you have other issues or concerns that are not addressed here, please leave a comment and I&#8217;ll do my best to help further!</p>
<p>If you don&#8217;t like the trouble caused by dealing with Ruby on Rails on DreamHost, check out <a href="http://blog.codahale.com/2006/06/19/time-for-a-grown-up-server-rails-mongrel-apache-capistrano-and-you/">this article</a> for some ideas of good alternatives!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.glennfu.com/2008/02/01/deploying-ruby-on-rails-with-capistrano-on-dreamhost/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
