<?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>Strange Symphonies &#187; Ruby</title>
	<atom:link href="http://blog.aizatto.com/tag/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.aizatto.com</link>
	<description>Don't worry, be happy</description>
	<lastBuildDate>Sun, 25 Jul 2010 07:59:00 +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>git-deploy Released</title>
		<link>http://blog.aizatto.com/2010/05/15/git-deploy-released/</link>
		<comments>http://blog.aizatto.com/2010/05/15/git-deploy-released/#comments</comments>
		<pubDate>Sat, 15 May 2010 13:10:31 +0000</pubDate>
		<dc:creator>aizatto</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Capistrano]]></category>
		<category><![CDATA[FTP]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[git-deploy]]></category>
		<category><![CDATA[GitHub]]></category>
		<category><![CDATA[MIT License]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[SCP]]></category>
		<category><![CDATA[SFTP]]></category>
		<category><![CDATA[SSH]]></category>

		<guid isPermaLink="false">http://blog.aizatto.com/?p=3716</guid>
		<description><![CDATA[I am a big fan of Capistrano and in general, software deployment tools. Capistrano works by connecting to your server, and updating the software there. Most of my clients get their hosting from a shared server hosting package, where the server is shared amongst multiple people. This is great, as it lowers the cost of [...]]]></description>
			<content:encoded><![CDATA[<p>I am a big fan of <a href="http://www.capify.org/">Capistrano</a> and in general, software deployment tools.  Capistrano works by connecting to your server, and updating the software there.</p>
<p>Most of my clients get their hosting from a shared server hosting package, where the server is shared amongst multiple people. This is great, as it lowers the cost of hosting tremendously, but also the number of features the server comes with is reduced. Most shared server hosting providers allow FTP.</p>
<p>Sadly Capistrano requires one to have SSH access to the server. Thus Capistrano, isn't a feasible tool to use.  Unable to find a substitute, I developed my own called <a href="http://github.com/aizatto/git-deploy"><code>git-deploy</code></a>.</p>
<p><a href="http://github.com/aizatto/git-deploy"><code>git-deploy</code></a> will interact with <code>git</code> to only update relevant files on the server via FTP or SSH.</p>
<p>For example, if you only updated on file in your source code, you only need to upload one file, and not the whole directory. This makes uploading, more time and bandwidth efficient. Especially for time, as the script can be run from the command line, so you don't need to launch your upload program, select which files to upload, drag and drog, and wait. A lot of time can be saved.</p>
<p>This is done by storing a file called <code>REVISION</code> on the server, which we can compare with on the local machine.</p>
<p>I am personally using it now on <a href="http://blog.aizatto.com">this website</a>, and other production sites.</p>
<p>I am planning to create a Ruby Gem out of the plugin, but unfortunately the name <a href="http://rubygems.org/gems/git-deploy"><code>git-deploy</code></a> was taken. I am still looking for a new name, so if you have a suggestion, just drop me a comment.</p>
<p><code>git-deploy</code> is licensed under an <a href="http://github.com/aizatto/git-deploy/raw/master/MIT-LICENSE">MIT License</a>, so feel free to use, change, and build on top of my code.</p>
<p>To find out more about <code>git-deploy</code>, and how to set it up visit its <a href="http://github.com/aizatto/git-deploy">GitHub</a> page.</p>
<p>Happy Deploying!</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://blog.aizatto.com/2009/02/06/sessionlessbots/" title="SessionlessBots (February 6, 2009)">SessionlessBots</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2009/09/12/ruby-on-rails-git-pre-commit-hook/" title="Ruby on Rails git pre-commit hook (September 12, 2009)">Ruby on Rails git pre-commit hook</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2010/06/07/improving-ssh-connections/" title="Improving SSH Connections (June 7, 2010)">Improving SSH Connections</a> (1)</li>
	<li><a href="http://blog.aizatto.com/2007/06/28/firebuglogger-released/" title="FirebugLogger Released (June 28, 2007)">FirebugLogger Released</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2007/05/26/will-ruby-not-be-the-next-big-programming-language/" title="Will Ruby Not be the Next Big Programming language&quot;? (May 26, 2007)">Will Ruby Not be the Next Big Programming language&quot;?</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://blog.aizatto.com/2010/05/15/git-deploy-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails Finite State Machine Plugin: Workflow</title>
		<link>http://blog.aizatto.com/2009/12/07/ruby-on-rails-finite-state-machine-plugin-workflow/</link>
		<comments>http://blog.aizatto.com/2009/12/07/ruby-on-rails-finite-state-machine-plugin-workflow/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 17:54:03 +0000</pubDate>
		<dc:creator>aizatto</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Finite State Machine]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[RubyGems]]></category>
		<category><![CDATA[workflow]]></category>

		<guid isPermaLink="false">http://blog.aizatto.com/?p=3125</guid>
		<description><![CDATA[I've been using the acts_as_state_machine plugin for Ruby on Rails for ages, but I thought it was time I look for alternatives, to see if there has been any development in the Finite State Machine scene. I also started getting worried that even though acts_as_state_machine still works, development on it has pretty much been discontinued. [...]]]></description>
			<content:encoded><![CDATA[<p>I've been using the <a href="http://blog.aizatto.com/2007/05/24/ruby-on-rails-finite-state-machine-plugin-acts_as_state_machine/">acts_as_state_machine plugin for Ruby on Rails</a> for ages, but I thought it was time I look for alternatives, to see if there has been any development in the Finite State Machine scene.  I also started getting worried that even though <code>acts_as_state_machine</code> still works, development on it has pretty much been discontinued. Good or bad, you can't really say.</p>
<p>Lucky me. I found one, and a pretty great one.</p>
<p>Introducing <a href="http://github.com/geekq/workflow">Workflow</a>, your alternate Finite State Machine for Ruby on Rails.</p>
<h3><code>acts_as_state_machine</code> vs Workflow</h3>

<p>At its core acts_as_state_machine and Workflow function exactly the same way. Feature wise Workflow wins out as it makes it easier to manage the callbacks. Workflow is more up to date, and I personally prefer its syntax a lot better than acts_as_state_machine.</p>
<p>Workflow's syntax looks a lot more like a Domain Specific Language.</p>
<h3>Installing Workflow</h3>

<h4>Installing Workflow as a Ruby on Rails Plugin</h4>

<p>Workflow can be installed either via Ruby Gems or a Ruby on Rails plugin.</p>
<p>As a Ruby on Rails plugin, go to the root folder of your Rails application and execute:</p>
<pre class="brush: plain;">./script/plugin install \
     git://github.com/geekq/workflow.git</pre>
<p class="block_important"><strong>Note:</strong> You may need Git installed </p>
<h4>Installing Workflow via Ruby Gems</h4>

<p>Likewise as a Ruby Gem, Workflow can be easily installed.  As your root user execute:</p>
<pre class="brush: plain;">gem install workflow</pre>
<p>We will need to update your <code>config/environments.rb</code>, and in the <code>Rails::Initializer.run</code> block we will need to add in <code>config.gem 'workflow'</code>.</p>
<p>Your <code>config/environments.rb</code> may look like so:</p>
<pre class="brush: ruby;">
Rails::Initializer.run do |config|
  ...
  config.gem 'workflow'
  ..
end
</pre>
<h3>Using Workflow</h3>

<p>Lets have a look at a sample code, featuring a Person.</p>
<pre class="brush: ruby;">
class Person &lt; ActiveRecord::Base
  include Workflow
  workflow do
    state :sleeping do
      event :shower, :transitions_to =&gt; :showering
      event :work, :transitions_to =&gt; :working
    end

    state :showering do
      event :sleep, :transitions_to =&gt; :sleeping
      event :work, :transitions_to =&gt; :working
      event :date, :transitions_to =&gt; :dating do |romantic_interest|
        successful = self.flirt(romantic_interest)
        halt unless successful
      end
    end

    state :working do
      event :shower, :transitions_to =&gt; :showering
    end

    state :dating do
      event :shower, :transitions_to =&gt; :showering
      event :sleep, :transitions_to =&gt; :showering
      event :work, :transitions_to =&gt; :showering
    end
  end
end
</pre>
<p class="block_important"><strong>Note:</strong> Workflow makes the assumption that the state of your model is saved in a field called <code>workflow_state</code>. </p>
<p>In <strong>line 2</strong> we have to specifically include include Workflow into our model. From there we begin describing the workflow by opening up a <code>workflow</code> block. Inside we define what states the model is going to contain, and what events can be fired to transition the model from one state to another.</p>
<p>The <strong>initial state of a model is the first state defined</strong>, in this case it is the <code>sleeping</code> state. States are defined in a <code>state</code> block as seen on <strong>lines 4, 9, 17, and 23</strong>. We have four states here: <code>sleeping</code>, <code>working</code>, <code>showering</code>, <code>dating</code>. Possible events a state may fire are contained within the <code>state</code> block as an <code>event</code> method. These events describe which state they would transition to if they were fired.</p>
<p>Methods are created every time you define a <code>state</code> or <code>event</code>. The method created when you define is a state tests wether or not the state is within a particular state, ie <code>person.sleeping?</code>. The methods created when you define an event is the event itself, ie <code>person.sleep!</code>.</p>
<p>There is also an additional method <code>current_state</code>, where you can investigate the current state of the object.</p>
<p>Given our example model above, these methods were created for our model:</p>
<p><code></p>
<ul>
<li>sleeping?</li>
<li>showering?</li>
<li>working?</li>
<li>dating?</li>
<li>sleep!</li>
<li>work!</li>
<li>shower!</li>
<li>date!</li>
<li>current_state</li>
</ul>
<p></code></p>
<h3>Events</h3>

<p>Events help you to transition from one state to another. So suppose your person is sleeping, and you want him to shower, well we'll just call shower!.</p>
<pre class="brush: ruby;">
person.current_state # &quot;sleeping&quot;
person.shower!
person.current_state # &quot;showering&quot;
</pre>
<p class="block_important"><strong>Note:</strong> When firing an event, Workflow calls <code>ActiveRecord::Base.update_attribute</code>. This means that <strong>only your record's state will be saved in the database</strong>, any other changes to the record are not. You still have to call <code>ActiveRecord::Base.save</code>. It also <strong>doesn't call any validations.</strong> Validations will be handled by your guards, which will be discussed later. Calling an event from a new unsaved record, will save the record into the database. </p>
<h3>Event Arguments</h3>

<p>You can even have your events accept arguments, this can be see on <strong>line 12</strong>, in the <code>:date</code> block.</p>
<pre class="brush: ruby; first-line: 12;">
    state :showering do
      event :sleep, :transitions_to =&gt; :sleeping
      event :work, :transitions_to =&gt; :working
      event :date, :transitions_to =&gt; :dating do |romantic_interest|
        successful = self.flirt(romantic_interest)
        halt unless successful
      end
    end
</pre>
<p class="block_important"><strong>Note:</strong> The scope of the block is within the instance. Treat it as any other method. <code>self</code> refers to the instance itself. <code>flirt</code> is a method defined in the instance. You would have to define the <code>flirt</code> method yourself. </p>
<p>Lets have a look at an example:</p>
<pre class="brush: ruby;">
person.current_state # showering

romantic_interest = Person.new
person.date! romantic_interest
person.current_state # dating
</pre>
<p>With events being able to accept arguments, this gives us a wider range of flexibility on handling and organizing the flow of your model. But they can get more powerful with callbacks.</p>
<h3>Callbacks</h3>

<p>A <code>state</code> also includes two callbacks. One for entering the state, and one for exiting the state.</p>
<p>Like the <code>event</code> blocks, the callback blocks also accept arguments.</p>
<p>You can define a <code>state</code>'s callback like so:</p>
<pre class="brush: ruby;">
state :sleeping do
  event :shower, :transitions_to =&gt; :showering
  event :work, :transitions_to =&gt; :working

  on_entry do |prior_state, triggering_event, *event_args|
    # code
  end

  on_exit do |new_state, triggering_event, *event_args|
    # code
  end
end
</pre>
<ul>
<li>The <code>on_entry</code> callback is called <strong>when a person enters the sleeping state</strong>.</li>
<li>The <code>on_exit</code> callback is called <strong>when a person exits the sleeping state</strong>.</li>
</ul>
<p>You can also define your callbacks outside of the <code>state</code> block and in your model itself as methods:</p>
<pre class="brush: ruby;">
state :sleeping do
  event :shower, :transitions_to =&gt; :showering
  event :work, :transitions_to =&gt; :working
end

def on_sleeping_entry(prior_state, triggering_event, *event_args)
  # code
end

def on_sleeping_exit(new_state, triggering_event, *event_args)
  # code
end
</pre>
<p class="block_important"><strong>Note:</strong> Notice the naming convention of the method name? To use this method, the callback is called <code>on_ + state name + _entry</code>, and <code>on_ + state name + _entry</code>. </p>
<p><strong>The arguments for the block and method are optional.</strong> Therefore for clarity, you may just enter:</p>
<pre class="brush: ruby;">
state :sleeping do
  event :shower, :transitions_to =&gt; :showering
  event :work, :transitions_to =&gt; :working

  on_entry do
    # code
  end

def on_sleeping_exit(new_state, triggering_event, *event_args)
  # code
end
</pre>
<h4>Global Callback</h4>

<p>This gets tedious if you want to monitor the transitions of every state change.  Don't worry, Workflow can handle that.</p>
<p>Workflow comes with an <code>on_transition</code> callback which is placed inside the <code>workflow</code> block:</p>
<pre class="brush: ruby;">
workflow do
  on_transition do |from, to, triggering_event, *event_args|
    puts &quot;from #{from} to #{to} via #{triggering_event}&quot;
  end
end
</pre>
<h4>Callback Order</h4>

<p>With all these callbacks, it gets a bit confusing. Here are <strong>Workflow's callbacks in context of ActiveRecord's callbacks</strong>:</p>
<ul>
<li>Workflow's in event</li>
<li>Workflow's on_transition</li>
<li>Workflow's on_exit</li>
<li>ActiveRecord::Base.before_save</li>
<li>ActiveRecord::Base.save</li>
<li>ActiveRecord::Base.after_save</li>
<li>Workflow's on_entry</li>
</ul>
<h3>Guarding States: halt!</h3>

<p>Using Workflow your model's validations do not work when an event is fired. In fact, only the model's <code>workflow_state</code> is saved when an event is fired, and not any other data.</p>
<p>In Workflow we can setup a guard, or a <code>halt</code>. This will prevent the transition from ever occurring, and provide us with the safety of having our models validated.</p>
<p>Guards can only be used inside the event block itself.  For example:</p>
<pre class="brush: ruby; first-line: 12;">
    state :showering do
      event :date, :transitions_to =&gt; :dating do |romantic_interest|
        successful = self.flirt(romantic_interest)
        halt unless successful
      end
    end
</pre>
<p>Assuming that the flirting with the romantic interest was unsuccessful, the person would still be in the the showering state.  All thanks to the <code>halt</code> on <strong>line 15</strong>.</p>
<p>This would run as follows:</p>
<pre class="brush: ruby;">
person.current_state # showering

romantic_interest = Person.new
person.date! romantic_interest
person.current_state # showering
</pre>
<p>Instead of just a <code>halt</code>, you can make it more destructive by calling <code>halt!</code> (with an exclamation mark) instead, which will throw the <code>Workflow::TransitionHalted</code> Exception instead.</p>
<h3>Conclusion</h3>

<p>As you can see Workflow is quite feature rich, and provides more flexibility than acts_as_state_machine. I would recommend using this over acts_as_state_machine any day. So why don't you experiment with it, and have some fun?</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://blog.aizatto.com/2009/11/26/finder-for-workflow-states/" title="Finder for Workflow States (November 26, 2009)">Finder for Workflow States</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2007/05/24/ruby-on-rails-finite-state-machine-plugin-acts_as_state_machine/" title="Ruby on Rails Finite State Machine Plugin: acts_as_state_machine (May 24, 2007)">Ruby on Rails Finite State Machine Plugin: acts_as_state_machine</a> (9)</li>
	<li><a href="http://blog.aizatto.com/2007/05/23/why-i-support-free-culture/" title="Why I Support Free Culture (May 23, 2007)">Why I Support Free Culture</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2009/11/11/swfupload-on-rails/" title="SWFUpload on Rails (November 11, 2009)">SWFUpload on Rails</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2009/09/12/ruby-on-rails-git-pre-commit-hook/" title="Ruby on Rails git pre-commit hook (September 12, 2009)">Ruby on Rails git pre-commit hook</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://blog.aizatto.com/2009/12/07/ruby-on-rails-finite-state-machine-plugin-workflow/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Finder for Workflow States</title>
		<link>http://blog.aizatto.com/2009/11/26/finder-for-workflow-states/</link>
		<comments>http://blog.aizatto.com/2009/11/26/finder-for-workflow-states/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 02:26:29 +0000</pubDate>
		<dc:creator>aizatto</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ActiveRecord]]></category>
		<category><![CDATA[ActiveRecord named_scope]]></category>
		<category><![CDATA[Finite State Machine]]></category>
		<category><![CDATA[geekq]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[workflow]]></category>

		<guid isPermaLink="false">http://blog.aizatto.com/?p=3032</guid>
		<description><![CDATA[Now a days for all my Finite State Machine needs on Ruby on Rails I use geekq's workflow. I find it much better to use than the previous popular Finite State Machine plugin on Rails, acts_as_state_machine. I need to locate all the models that are of a certain state, and thanks to named_scope. This can [...]]]></description>
			<content:encoded><![CDATA[<p>Now a days for all my Finite State Machine needs on Ruby on Rails I use <a href="http://github.com/geekq/workflow">geekq's workflow</a>.  I find it much better to use than the previous popular Finite State Machine plugin on Rails, <code><a href="http://blog.aizatto.com/2007/05/24/ruby-on-rails-finite-state-machine-plugin-acts_as_state_machine/">acts_as_state_machine</a></code>.</p>
<h3>named_scope</h3>

<p>I need to locate all the models that are of a certain state, and thanks to <code>named_scope</code>. This can be done quite easily.  Except when we have a lot of states I'd rather not write a <code>named_scope</code> for each individual state.  For example:</p>
<pre class="brush: ruby;">
class Order &lt; ActiveRecord::Base
  named_scope :completed, :conditions =&gt; { :workflow_state =&gt; 'completed' }
end
</pre>
<p>It would be encumbersome to write this multiple times.  I'd rather have a <code>named_scope</code> created for each state. This is my quick hack.</p>
<pre class="brush: ruby;">
class Order &lt; ActiveRecord::Base
  include Workflow
  workflow do
    state :new do
      ...
    end

    ...
  end

  (self.workflow_spec.states.keys - [:new]).each do |state|
    named_scope state, :conditions =&gt; { :workflow_state =&gt; state.to_s }
  end
end
</pre>
<p>After the workflow code you place you write:</p>
<pre class="brush: ruby; first-line: 11;">
  (self.workflow_spec.states.keys - [:new]).each do |state|
    named_scope state, :conditions =&gt; { :workflow_state =&gt; state.to_s }
  end
</pre>
<p>This iterates through each of our workflow states, and creates a <code>named_scope</code> for each one based on the name of the state.  So you can easily do <code>Order.completed</code> and find all completed Orders.</p>
<p class="block_important"><strong>Note:</strong> I had to remove <code>:new</code> (on line 12) from the array of keys as it would cause problems with my code.  This is caused from overwriting the <code>new</code> method. You can solve this by probably putting a prefix for the <code>named_scope</code> name. </p>
<p>I know it can be extracted to use <code>alias_method_chain</code> and modify the Workflow sourcecode, but I enjoy my hack.</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://blog.aizatto.com/2009/12/07/ruby-on-rails-finite-state-machine-plugin-workflow/" title="Ruby on Rails Finite State Machine Plugin: Workflow (December 7, 2009)">Ruby on Rails Finite State Machine Plugin: Workflow</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2007/05/24/ruby-on-rails-finite-state-machine-plugin-acts_as_state_machine/" title="Ruby on Rails Finite State Machine Plugin: acts_as_state_machine (May 24, 2007)">Ruby on Rails Finite State Machine Plugin: acts_as_state_machine</a> (9)</li>
	<li><a href="http://blog.aizatto.com/2007/06/04/fixtures-without-rails/" title="Fixtures Without Rails (June 4, 2007)">Fixtures Without Rails</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2007/05/23/why-i-support-free-culture/" title="Why I Support Free Culture (May 23, 2007)">Why I Support Free Culture</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2009/11/11/swfupload-on-rails/" title="SWFUpload on Rails (November 11, 2009)">SWFUpload on Rails</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://blog.aizatto.com/2009/11/26/finder-for-workflow-states/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SWFUpload on Rails</title>
		<link>http://blog.aizatto.com/2009/11/11/swfupload-on-rails/</link>
		<comments>http://blog.aizatto.com/2009/11/11/swfupload-on-rails/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 03:50:58 +0000</pubDate>
		<dc:creator>aizatto</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[restful-authentication]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[SWFUpload]]></category>

		<guid isPermaLink="false">http://blog.aizatto.com/?p=2901</guid>
		<description><![CDATA[SWFUpload is a Flash uploader, that enhances the experience of uploading. Some examples include the ability to select multiple files at once, and queue them up for upload. For more features, visit the SWFUpload website. This is a great tool if your website requires you to upload multiple files. But there are documented issues SWFUpload [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.swfupload.org/"><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  class="alignright size-full wp-image-2902" title="SWFUpload" src="http://blog.aizatto.com/wp-content/uploads/2009/11/swfupload.png" alt="SWFUpload" width="41" height="55" /></a></p>
<p class="block_important"><strong>Note:</strong> This has been tested with SWFUpload v2.2.0.1 and Ruby on Rails v2.3.4 </p>
<p class="block_important"><strong>Note:</strong> This is used together with <a href="http://github.com/technoweenie/restful-authentication">restful-authentication</a>. </p>
<p><a href="http://swfupload.org/">SWFUpload</a> is a Flash uploader, that enhances the experience of uploading.  Some examples include the ability to select multiple files at once, and queue them up for upload.  For more features, visit the <a href="http://swfupload.org/">SWFUpload</a> website. This is a great tool if your website requires you to upload multiple files.</p>
<p>But there are documented issues SWFUpload and using it with Ruby on Rails.</p>
<p>By default, when using SWFUpload with Ruby on Rails, SWFUpload works great. Everything works as documented, well at least as far as I can tell.  By default I mean:</p>
<ul>
<li>You are not using authentication (for example login)</li>
<li>If you are using authentication, but uploading to a page that doesn't require login</li>
</ul>
<h3>Problems with SWFUpload and Ruby on Rails</h3>

<p>SWFUpload breaks on Ruby on Rails when you using authentication, and when you have to upload to a page that requires login.  The result of doing so is that Rails will think your user is not currently logged in, and will deny the upload request possibly by redirecting the request to the login page.  This bug is caused Flash not being able to use the same session as your web browser.</p>
<p>Now when you Google, you will notice multiple methods of solving this problem.  Notably a fix to rack and the middleware.  Now I don't want to hack my rack, or middleware. Plus I found all the documentation rather confusing.</p>
<h3>swfupload.cookies.js</h3>

<p>Instead what I wanted to focus on, was in the tarball for SWFUpload. Inside I noticed a file called <code>swfupload.cookies.js</code>.  The file describes itself as:</p>
<blockquote><p>
Cookie Plug-in</p>
<p>This plug in automatically gets all the cookies for this site and adds them to the post_params.<br />
Cookies are loaded only on initialization.  The refreshCookies function can be called to update the post_params.<br />
The cookies will override any other post params with the same name.
</p></blockquote>
<p>When you include swfupload.cookies.js into your application, your <code>params</code> will include the keys and values from your cookies.  For example, if you had a cookie called "<code>auth_token</code>", with a value of "<code>d2f423cd5559645eb8e75230b9ce2648d59a7ad8</code>", it would appear in your params as <code>params[:auth_token] = 'd2f423cd5559645eb8e75230b9ce2648d59a7ad8'</code>.</p>
<p>This was the perfect tool I needed.</p>
<h3>Getting SWFUpload to work with Rails</h3>
<br />
<p class="block_important"><strong>Note:</strong> Once again, this tutorial is for use with <a href="http://github.com/technoweenie/restful-authentication">restful-authentication</a>.  We will assume that your User model is called "<code>User</code>", and your Session controller is called "<code>SessionsController</code>". We will also assume that the swfupload files are in <code>/public/javascripts</code>  </p></p>
<p><h4>Using swfupload.cookies.js</h4>
</p>
<p>In your Rails app, include <code>swfupload.cookies.js</code>. I decided to put it after my <code>swfupload.js</code>.</p>
<pre class="brush: plain;">
  &lt;%= javascript_include_tag 'swfupload.js' %&gt;
  &lt;%= javascript_include_tag 'swfupload.cookies.js' %&gt;
</pre>
<p><h4>Modify Your Sessions Controller</h4>
</p>
<p>If you open up your Sessions controller ( <code>/app/controllers/sessions_controller</code> <img src="http://blog.aizatto.com/wp-content/plugins/aizatto_blocks/images/script.png" alt="File" title="File" /> ) you will see a <code>create</code> method.  This is where your <code>User</code> is authenticated, and their session established.</p>
<pre class="brush: ruby;">
  def create
    logout_keeping_session!
    user = User.authenticate(params[:login], params[:password])
    if user
      # Protects against session fixation attacks, causes request forgery
      # protection if user resubmits an earlier form using back
      # button. Uncomment if you understand the tradeoffs.
      # reset_session
      self.current_user = user
      new_cookie_flag = (params[:remember_me] == '1')
      handle_remember_cookie! new_cookie_flag
      flash[:notice] = 'Logged in successfully'
    else
      note_failed_signin
      @login       = params[:login]
      @remember_me = params[:remember_me]
    end
    redirect_back_or_default('/')
  end
</pre>
<p>Now we need to change lines 10-11.<br />
From:</p>
<pre class="brush: ruby; first-line: 10;">
      new_cookie_flag = (params[:remember_me] == '1')
      handle_remember_cookie! new_cookie_flag
</pre>
<p>To:</p>
<pre class="brush: ruby; first-line: 10;">
      handle_remember_cookie! true
</pre>
<p>Yes, we are going to make the <code>User</code> remember the cookie every time he logs in.</p>
<p><h4>Modifying lib/authenticated_system.rb</h4>
</p>
<p>Now for all this to work we need to edit <code>lib/authenticated_system.rb</code>.</p>
<p>Look for the <code>current_user</code>.</p>
<pre class="brush: ruby;">
    def current_user
      @current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_user == false
    end
</pre>
<p>Now we are going to add a new method call to that, and change the method <code>current_user</code> to:</p>
<pre class="brush: ruby;">
    def current_user
      @current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie || login_from_params) unless @current_user == false
    end
</pre>
<p>Now we create a new method called <code>login_from_params</code>.</p>
<pre class="brush: ruby;">
    # Created specifically for swfupload, as the cookie can't be passed via flash, and is instead passed via a post param
    def login_from_params
      binder = params[:auth_token] &amp;&amp; User.find_by_remember_token(params[:auth_token])
      if user &amp;&amp; user.remember_token?
        self.current_user = binder
      end
    end
</pre>
<p>This is where the magic happens. The user will be logged in based on their <code>:auth_token</code>.</p>
<p><h4>Testing</h4>
</p>
<p>Make sure you log out the user, and login again as we have to create the cookie.</p>
<p><h3>Conclusion</h3>

<p>There you have it!  A working SWFUpload with Rails.  Enjoy.</p>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://blog.aizatto.com/2007/05/23/why-i-support-free-culture/" title="Why I Support Free Culture (May 23, 2007)">Why I Support Free Culture</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2009/09/12/ruby-on-rails-git-pre-commit-hook/" title="Ruby on Rails git pre-commit hook (September 12, 2009)">Ruby on Rails git pre-commit hook</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2009/12/07/ruby-on-rails-finite-state-machine-plugin-workflow/" title="Ruby on Rails Finite State Machine Plugin: Workflow (December 7, 2009)">Ruby on Rails Finite State Machine Plugin: Workflow</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2007/05/24/ruby-on-rails-finite-state-machine-plugin-acts_as_state_machine/" title="Ruby on Rails Finite State Machine Plugin: acts_as_state_machine (May 24, 2007)">Ruby on Rails Finite State Machine Plugin: acts_as_state_machine</a> (9)</li>
	<li><a href="http://blog.aizatto.com/2007/06/01/ruby-and-open-classes/" title="Ruby and Open Classes (June 1, 2007)">Ruby and Open Classes</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://blog.aizatto.com/2009/11/11/swfupload-on-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating an iPay88 Signature in Ruby</title>
		<link>http://blog.aizatto.com/2009/10/01/generating-an-ipay88-signature-in-ruby/</link>
		<comments>http://blog.aizatto.com/2009/10/01/generating-an-ipay88-signature-in-ruby/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 09:55:55 +0000</pubDate>
		<dc:creator>aizatto</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[iPay88]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://blog.aizatto.com/?p=1554</guid>
		<description><![CDATA[When using the iPay88 services, you are required to calculate a signature to verify that the transaction was correct. Now iPay88 provides examples in ASP, ASP.Net, JavaScript, and PHP, but not in Ruby. So I thought I would go ahead and provide one: require 'digest/sha1' require 'base64' def ipay88_signature(string) Base64.encode64(Digest::SHA1.hexdigest(string).scan(/../).collect { &#124;a&#124; a.hex.chr }.join).chomp end [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ipay88.com/"><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  src="http://blog.aizatto.com/wp-content/uploads/2009/10/ipay88.gif" alt="ipay88" title="ipay88" width="92" height="108" class="alignright size-full wp-image-1555" /></a><br />
When using the iPay88 services, you are required to calculate a signature to verify that the transaction was correct.</p>
<p>Now iPay88 provides examples in ASP, ASP.Net, JavaScript, and PHP, but not in Ruby.  So I thought I would go ahead and provide one:</p>
<pre class="brush: ruby; gutter: false;">
require 'digest/sha1'
require 'base64'

def ipay88_signature(string)
  Base64.encode64(Digest::SHA1.hexdigest(string).scan(/../).collect { |a| a.hex.chr }.join).chomp
end
</pre>

	<h4>Related posts</h4>
	<ul class="st-related-posts">
	<li><a href="http://blog.aizatto.com/2007/05/26/will-ruby-not-be-the-next-big-programming-language/" title="Will Ruby Not be the Next Big Programming language&quot;? (May 26, 2007)">Will Ruby Not be the Next Big Programming language&quot;?</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2007/05/23/why-i-support-free-culture/" title="Why I Support Free Culture (May 23, 2007)">Why I Support Free Culture</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2007/05/30/what-version-of-ruby-am-i-using/" title="What Version of Ruby Am I Using? (May 30, 2007)">What Version of Ruby Am I Using?</a> (0)</li>
	<li><a href="http://blog.aizatto.com/2006/11/11/unexpected-behavior-of-rubys-rangemin-rangemax/" title="Unexpected behavior of Ruby&#8217;s Range.min Range.max (November 11, 2006)">Unexpected behavior of Ruby&#8217;s Range.min Range.max</a> (1)</li>
	<li><a href="http://blog.aizatto.com/2006/11/11/unexpected-behavior-of-rubys-rangemin-rangemax-2/" title="Unexpected behavior of Ruby&#039;s Range.min Range.max (November 11, 2006)">Unexpected behavior of Ruby&#039;s Range.min Range.max</a> (0)</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://blog.aizatto.com/2009/10/01/generating-an-ipay88-signature-in-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
