<?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>Ruby Fleebie &#187; short &amp; sweet</title>
	<atom:link href="http://www.rubyfleebie.com/category/short_and_sweet/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rubyfleebie.com</link>
	<description>Because programming should be fun</description>
	<lastBuildDate>Wed, 25 Jan 2012 18:06:55 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Interacting with MongoDB using Rails 3 and MongoMapper</title>
		<link>http://www.rubyfleebie.com/interacting-with-mongodb-using-rails-3-and-mongomapper/</link>
		<comments>http://www.rubyfleebie.com/interacting-with-mongodb-using-rails-3-and-mongomapper/#comments</comments>
		<pubDate>Thu, 18 Nov 2010 18:30:03 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/?p=247</guid>
		<description><![CDATA[MongoDB is an opensource document-oriented database in the vein of CouchDB. It’s been a while since I wanted to try this kind of database on a Rails project. After reading this nice tutorial today I decided to take some time to create a sample Rails 3 app and put it on github.
I chose to use [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.mongodb.org/">MongoDB</a> is an opensource document-oriented database in the vein of <a href="http://couchdb.apache.org/">CouchDB</a>. It’s been a while since I wanted to try this kind of database on a Rails project. After reading this nice <a href="http://www.mongodb.org/display/DOCS/Rails+3+-+Getting+Started">tutorial</a> today I decided to take some time to create a sample Rails 3 app and put it on <a href="https://github.com/flamontagne/mongomapper-rails3-sample">github</a>.</p>
<p>I chose to use <a href="https://github.com/jnunemaker/mongomapper">MongoMapper</a>, a ruby object mapper for Mongo. MongoMapper uses ActiveModel and let you interact with a MongoDB database in a very <em>ActiveRecord way</em>. </p>
<p>Hope this sample app will help you getting started with MongoDB!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/interacting-with-mongodb-using-rails-3-and-mongomapper/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How to add methods to existing classes</title>
		<link>http://www.rubyfleebie.com/how-to-add-methods-to-existing-classes/</link>
		<comments>http://www.rubyfleebie.com/how-to-add-methods-to-existing-classes/#comments</comments>
		<pubDate>Tue, 29 Jun 2010 16:12:52 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/?p=76</guid>
		<description><![CDATA[A quick and easy tip today. It won&#8217;t impress the veteran ruby developer, but it will impress every ruby newcomers, guaranteed!
Say I have a horse racing ruby application that allow people to know information about every competing horses. I have an input box that people can use to enter the name of a horse. Once [...]]]></description>
			<content:encoded><![CDATA[<p>A quick and easy tip today. It won&#8217;t impress the veteran ruby developer, but it will impress every ruby newcomers, guaranteed!</p>
<p>Say I have a horse racing ruby application that allow people to know information about every competing horses. I have an input box that people can use to enter the name of a horse. Once they click OK, information about the specified horse is displayed to the user.</p>
<p>Instead of going the traditonal route, how about adding a &#8220;horse&#8221; method to the String class? It could not be easier :</p>
<pre class="brush: ruby; title: ;">
HORSES = [
  {
    :name =&gt; &quot;Jolly Jumper&quot;,
    :also_known_as =&gt; [&quot;Smart Arse&quot;,&quot;Lucky Luke friend&quot;],
    :speed =&gt; 3, :intelligence =&gt; 30,
    :favorite_quote =&gt; &quot;I am a horse, I don't have quotes&quot;
  },

  {
    :name =&gt; &quot;Incredibly Bad&quot;,
    :also_known_as =&gt; [&quot;Shame&quot;,&quot;The Pathetic&quot;],
    :speed =&gt; 2, :intelligence =&gt; 4,
    :favorite_quote =&gt; &quot;If you still put your money on me, you only have yourself to blame&quot;
  },

  {
    :name =&gt; &quot;Fast And Furious&quot;,
    :also_known_as =&gt; [&quot;The Strong Rebel&quot;,&quot;The Furious One&quot;],
    :speed =&gt; 50, :intelligence =&gt; 15,
    :favorite_quote =&gt; &quot;I am fast&quot;
  },

 {
    :name =&gt; &quot;Slow and Jerky&quot;,
    :also_known_as =&gt; [&quot;Tender&quot;,&quot;Terrible Choice&quot;],
    :speed =&gt; 1, :intelligence =&gt; 10,
    :favorite_quote =&gt; &quot;Pick me once, regret it for a lifetime.&quot;
  }
]

class String
  def horse
    res = HORSES.select { |h| h[:name] == self || h[:also_known_as].include?(self)}
    res.first if res.length&gt;0
  end
end

#Then you can do stuff like this :
horse = &quot;Tender&quot;.horse
if horse
	puts &quot;#{horse[:name]}, also known as #{horse[:also_known_as].join(&quot;, &quot;)}, has a speed of #{horse[:speed]} and an intelligence of #{horse[:intelligence]}. In its free time, this horse like to become all philosophic, look at the sky and say : '#{horse[:favorite_quote]}'&quot;
else
	puts &quot;This horse doesn't exists in our records&quot;
end
</pre>
<p>Talk about some great syntactic ruby sugar!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/how-to-add-methods-to-existing-classes/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>RESTful admin controllers and views with Rails</title>
		<link>http://www.rubyfleebie.com/restful-admin-controllers-and-views-with-rails/</link>
		<comments>http://www.rubyfleebie.com/restful-admin-controllers-and-views-with-rails/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 15:09:49 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/restful-admin-controllers-and-views-with-rails/</guid>
		<description><![CDATA[You want a RESTful Rails app with a backend administration? The worst thing to do in my opinion is to use the same controllers for the public and the admin side. At first, it might look wise to do this. I mean, if you have a &#8220;books&#8221; resource, it would be logical that all methods [...]]]></description>
			<content:encoded><![CDATA[<p>You want a RESTful Rails app with a backend administration? The worst thing to do in my opinion is to use the same controllers for the public and the admin side. At first, it might look wise to do this. I mean, if you have a &#8220;books&#8221; resource, it would be logical that all methods related to books go in the same controller, right? Well, logical or not&#8230; I suggest you never do this because your application will become a real mess in no time. Personally, I did it once and will never get caught again!</p>
<p>Exemple of a mess in a controller :</p>
<pre class="brush: ruby; title: ;">
def index
  if administrator?
    @books = Book.all
  else
    @books = Book.published
  end
</pre>
<p>Example of a mess in a view :</p>
<pre class="brush: ruby; title: ;">
&lt;%if administrator?%&gt;
&lt;%=render :partial =&gt; &quot;admin_index&quot;%&gt;
&lt;%else%&gt;
&amp;lt;h1&amp;gt;Published books&amp;lt;/h1&amp;gt;
bla bla bla
&lt;%end%&gt;
</pre>
<p>If you go that route, be prepared to make your fingers bleed because you will write tons of confusing and ugly &#8220;if&#8221; statements everywhere.  Most of the time anyway, what you need to do with the resources is completely different depending if you&#8217;re on the admin or public side, so you&#8217;re better to separate them.</p>
<p><strong>Step #1 : Generating the controllers</strong><br />
To generate a public controller, you do like you always do : ./script/generate controller books</p>
<p>To generate its admin counterpart, you simply do this : ./script/generate controller admin/books</p>
<p>Rails will generate the controller in controllers/admin/books_controller.rb and a folder for the views in views/admin/books</p>
<p><strong>Step #2 : Configuring the routes</strong><br />
One route for the public side :</p>
<pre class="brush: ruby; title: ;">map.resources :books, :only =&gt; [:index, :show]</pre>
<p>One route for the admin side</p>
<pre class="brush: ruby; title: ;">
map.namespace :admin do |admin|
  admin.resources :books
  admin.resources :some_other_resource
end
</pre>
<p>Now your namespaced controller has its own named urls as well : admin_books_url, edit_admin_book_url and so on&#8230;</p>
<p><strong>Step #3 : Get the &#8220;form_for&#8221; url right</strong></p>
<pre class="brush: ruby; title: ;">
&lt;%form_for [:admin, @book] do |f|%&gt;
   &lt;%=f.text_field :title%&gt;
   &lt;%=f.submit &quot;Save&quot;%&gt;
&lt;%end%&gt;
</pre>
<p>That way Rails will correctly call the update/create method in controllers/admin/books_controller.rb instead of the one in controllers/books_controller.rb</p>
<p><strong>A final note</strong><br />
The controllers and the views are best kept separated but NOT the model which should always remain unique in your app. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/restful-admin-controllers-and-views-with-rails/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Encryption with Alphanumeric output</title>
		<link>http://www.rubyfleebie.com/encryption-with-alphanumeric-output/</link>
		<comments>http://www.rubyfleebie.com/encryption-with-alphanumeric-output/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 16:10:28 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/encryption-with-alphanumeric-output/</guid>
		<description><![CDATA[What if you want to generate reasonably short alphanumeric user activation codes without having to store anything in a DB (so in this case generating random user codes won&#8217;t do) ? Why would someone need this? Think about an application where you want to print activation cards and sell them to your customers. The customer [...]]]></description>
			<content:encoded><![CDATA[<p>What if you want to generate reasonably short alphanumeric user activation codes <strong>without having to store anything in a DB</strong> (so in this case generating random user codes won&#8217;t do) ? Why would someone need this? Think about an application where you want to print activation cards and sell them to your customers. The customer then login to your website, put the activation code that is printed on its card&#8230; and bingo : they are activated.</p>
<p>So, how to do this? With encryption, of course.</p>
<p>The thing is that most encryption algorithms will generate ciphers with non-friendly characters, like : Òèç`{&#038;[ùỲgǛ... so bad for readability. It seems complicated at first but finally one solution turns out to be fairly simple :</p>
<p>Step #1</p>
<pre lang='ruby'>sudo gem install crypt</pre>
<p>Step #2</p>
<pre lang='ruby'>blowfish = Crypt::Blowfish.new(SOME_KEY)
crypted_but_readable = blowfish.encrypt_block("12345678").unpack("H*")
</pre>
<p>Step #3</p>
<pre lang='ruby'>
  crypted_block = params[:some_crypted_but_readable_block].to_s
  if crypted_block.length == 16
    blowfish = Crypt::Blowfish.new(THE_SAME_KEY)
    decrypted_block = blowfish.decrypt_block(crypted_block.to_a.pack(&#8220;H*&#8221;))
    #do something with decrypted block
  end
</pre>
<p>The Blowfish algorithm takes 8-bytes blocks only... so you have to take that into account when you generate your keys.  The unpack("H*) and pack("H*") parts are the most important. It simply encodes/decodes the block in hexadecimal.  So, here we are, you have a readable &#038; decryptable 16-chars cipher that looks like : 9048bb8f56eddd47. You can even display the codes into chunks of 4 characters and it gives you the following friendly code : 9048-bb8f-56ed-dd47</p>
<p>Tip: Associate to each code a SHA-1 hashed password (which is the result of activation code + some salt) and you have a pretty safe account activation procedure that doesn't pollute your database. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/encryption-with-alphanumeric-output/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Last deployment date with Rails and Capistrano</title>
		<link>http://www.rubyfleebie.com/last-deployment-date/</link>
		<comments>http://www.rubyfleebie.com/last-deployment-date/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 14:49:00 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/last-deployment-date/</guid>
		<description><![CDATA[When you are developing an app or a website for your client, it is pretty common to setup a sandbox environment where your client can test and see the application while it is still in development. One thing I find useful is to display the last deployment date on the home page.
Here is a quick [...]]]></description>
			<content:encoded><![CDATA[<p>When you are developing an app or a website for your client, it is pretty common to setup a sandbox environment where your client can test and see the application while it is still in development. One thing I find useful is to display the last deployment date on the home page.</p>
<p>Here is a quick and easy way to automate the process :</p>
<p><strong>Step #1 (we can have lots of fun)</strong><br />
I will consider that you use capistrano for deploying your app. The only thing you have to do in your capistrano recipe is to &#8220;touch&#8221; a dummy file to update its modification date.</p>
<pre lang='ruby'>
namespace :deploy do
  desc 'Restart My App'
  task :restart, :roles => :app do
    run "touch #{current_path}/last_deploy"
  end
end
</pre>
<p><strong>Step #2 (there&#8217;s so much we can do)</strong><br />
Now in application_controller, add a before_filter like this</p>
<pre lang='ruby'>
before_filter :last_deploy

def last_deploy
  @last_deploy = File.new("last_deploy").atime rescue Time.now
end
</pre>
<p><strong>Step #3 (it&#8217;s just you and me)</strong><br />
Display the date in the layout or in the view of your choice</p>
<pre lang='ruby'>
<%= "Last deployment : #{@last_deploy}"%>
</pre>
<p>Edit : Oh, dear readers, I just want to let you know that RubyFleebie is now on <a href="http://twitter.com/rubyfleebie">Twitter</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/last-deployment-date/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Try Monit to manage your daemons</title>
		<link>http://www.rubyfleebie.com/try-monit-to-manage-your-daemons/</link>
		<comments>http://www.rubyfleebie.com/try-monit-to-manage-your-daemons/#comments</comments>
		<pubDate>Thu, 10 Sep 2009 19:14:07 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/try-monit-to-manage-your-daemons/</guid>
		<description><![CDATA[Hello there,
I&#8217;m sorry for not updating my blog more often. Now is the time to use the best excuse in the world that will make me look like a busy businessman and you will all be impressed. Here we go : I don&#8217;t have the time!
I know a lot of you are using GOD to [...]]]></description>
			<content:encoded><![CDATA[<p>Hello there,</p>
<p>I&#8217;m sorry for not updating my blog more often. Now is the time to use the best excuse in the world that will make me look like a busy businessman and you will all be impressed. Here we go : I don&#8217;t have the time!</p>
<p>I know a lot of you are using <a href="http://god.rubyforge.org/">GOD</a> to keep your daemons / processes alive. I really don&#8217;t want to say bad things about GOD (I can&#8217;t because I never tried it)&#8230; <a href="http://blog.bradgessler.com/use-monit-with-rails-not-god">but I DID read some really nasty things about it</a> and somehow it convinced me to try an alternative : <a href="http://mmonit.com/">Monit</a>.</p>
<p>The biggest advantage with Monit is that it is written in C instead of ruby&#8230; so it doesn&#8217;t leak and it appears to be faster. It is also pretty easy to configure. Here is a very basic monit configuration file:</p>
<pre lang='shell'>
set daemon 60

set httpd port 2812 address localhost
     allow localhost 

check process my_process
  with pidfile /home/apps/someapp/my_process.pid
  start program = "/home/apps/someapp/my_process start"
  stop program = "/home/apps/someapp/my_process stop"
</pre>
<p>Then, you start the monit daemon by typing : <strong>monit</strong></p>
<p>It will poll the monit configuration file every minute (this is the <em>set daemon 60</em> part) and will restart &#8216;my_process&#8217; whenever it is not running. Of course this is an extremely simple use case and there are a lot more configuration options you can play with. Have a look at the <a href="http://mmonit.com/monit/documentation/monit.html">documentation</a> for more info.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/try-monit-to-manage-your-daemons/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Geany IN, Komodo OUT</title>
		<link>http://www.rubyfleebie.com/geany-in-komodo-out/</link>
		<comments>http://www.rubyfleebie.com/geany-in-komodo-out/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 16:45:33 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/geany-in-komodo-out/</guid>
		<description><![CDATA[First of all, I&#8217;d like to deny the rumor that I am dead.
I&#8217;m struggling since day #1 to find a good code editor for ruby. Mac users are happy with their textmate&#8230; but what&#8217;s left for us linux users? I tried gedit, vim, scribes and eclipse (with the aptana plugin) but wasn&#8217;t happy enough with [...]]]></description>
			<content:encoded><![CDATA[<p>First of all, I&#8217;d like to deny the rumor that I am dead.</p>
<p>I&#8217;m struggling since day #1 to find a good code editor for ruby. Mac users are happy with their textmate&#8230; but what&#8217;s left for us linux users? I tried gedit, vim, scribes and eclipse (with the aptana plugin) but wasn&#8217;t happy enough with any of them. <a href="http://www.rubyfleebie.com/komodo-edit-a-great-editor-for-dynamic-languages/">I thought I found a real gem in Komodo edit</a>, but that&#8217;s just not doing it for me anymore. Komodo is a great editor but it is plagued with a huge problem : it is slow and unresponsive. Sometime you start typing code and you won&#8217;t see what you just typed on the screen. Wait a few seconds and boom, here is your code&#8230; full of typos. </p>
<p>Now that my honey moon with Komodo is over, I searched the web and found <a href="http://www.geany.org/Main/HomePage">Geany</a>, a light-weight code editor that works for linux and windows. I&#8217;m very satisfied with it so far. Instead of making a half-assed review of the editor, I think you should try it by yourself and decide if you like it or not.</p>
<p><strong>Off topic note :</strong></p>
<p>Those who liked the &#8220;in depth&#8221; posts I was doing in the early days of this blog might be disappointed with the kind of posts I&#8217;m doing now. I&#8217;m thinking about this for some time and I can say that <strong>I am planning to start writing like those early days</strong>. Why? Well, simply because I found it more enjoyable. The problem however is finding the time to write longer and more in-depth posts. I am currently quite busy with <a href="http://www.timmyontime.com">TimmyOnTime</a> <a href="http://www.azankatech.com">and</a> <a href="http://behindtheclock.timmyontime.com">other</a> <a href="http://github.com/flamontagne/xmppbot/">projects</a> so unfortunately RubyFleebie is suffering from it. I want to thank you for your patience&#8230; it amazes me that I still have all those subscribers and daily readers.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/geany-in-komodo-out/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Get the intersection of 2 arrays</title>
		<link>http://www.rubyfleebie.com/get-the-intersection-of-2-arrays/</link>
		<comments>http://www.rubyfleebie.com/get-the-intersection-of-2-arrays/#comments</comments>
		<pubDate>Fri, 03 Oct 2008 21:39:25 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/get-the-intersection-of-2-arrays/</guid>
		<description><![CDATA[Pretty easy stuff today, but this is not something you may need to do often so maybe you don&#8217;t know how to do it.
Say I have these 2 arrays :
colors1 = [:blue, :red, :green, :orange, :purple]
colors2 = [:yellow, :cyan, :green, :blue, :purple]
Now what if I want a new array that contains only the elements present [...]]]></description>
			<content:encoded><![CDATA[<p>Pretty easy stuff today, but this is not something you may need to do often so maybe you don&#8217;t know how to do it.</p>
<p>Say I have these 2 arrays :</p>
<pre lang="ruby">colors1 = [:blue, :red, :green, :orange, :purple]
colors2 = [:yellow, :cyan, :green, :blue, :purple]</pre>
<p>Now what if I want a new array that contains only the elements present in both arrays?</p>
<pre lang="ruby">beautiful_colors = colors1 &#038; colors2
#beautiful_colors contains [:blue, :green, :purple]</pre>
<p>Have a nice weekend!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/get-the-intersection-of-2-arrays/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Need support for has_many through with has_one in the &#8220;bridge table&#8221;</title>
		<link>http://www.rubyfleebie.com/need-support-for-has_many-through-with-has_one-in-the-bridge-table/</link>
		<comments>http://www.rubyfleebie.com/need-support-for-has_many-through-with-has_one-in-the-bridge-table/#comments</comments>
		<pubDate>Sat, 13 Sep 2008 18:02:51 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/need-support-for-has_many-through-with-has_one-in-the-bridge-table/</guid>
		<description><![CDATA[has_many :through limitations]]></description>
			<content:encoded><![CDATA[<p>Let me expose the problem with an example :</p>
<p>Cart model (as in : shopping cart)</p>
<pre lang="ruby">class Cart < ActiveRecord::Base
  has_one :bill
  belongs_to :user
end</pre>
<p>Bill model</p>
<pre lang="ruby">class Bill < ActiveRecord::Base
  belongs_to :cart
end</pre>
<p>User</p>
<pre lang="ruby">class User < ActiveRecord::Base
  has_many :carts
  has_many :bills, :through => :carts #<== Doesn't work... no user.bills for you!
end</pre>
<p>Basically, because the "through" table links the destination table with a has_one relationship, ActiveRecord complains with : <em>Invalid source reflection macro :has_one for has_many :bills, :through => :carts.  Use :source to specify the source reflection.</em></p>
<p>Someone on Rails Trac already created a <a href="http://dev.rubyonrails.org/ticket/4996">ticket</a> about this issue <strong>2 years ago</strong>. Can we expect this feature to be officially supported in the future? Let's hope so.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/need-support-for-has_many-through-with-has_one-in-the-bridge-table/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>acts_as_state_machine and variable initial states</title>
		<link>http://www.rubyfleebie.com/acts_as_state_machine-and-variable-initial-states/</link>
		<comments>http://www.rubyfleebie.com/acts_as_state_machine-and-variable-initial-states/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 15:54:16 +0000</pubDate>
		<dc:creator>Frank</dc:creator>
				<category><![CDATA[short & sweet]]></category>

		<guid isPermaLink="false">http://www.rubyfleebie.com/acts_as_state_machine-and-variable-initial-states/</guid>
		<description><![CDATA[acts_as_state_machine is a great plugin really useful when you want to add constraints and behavior to your model objects.
Note : Those who don&#8217;t know what this plugin is all about should stop reading right there or risk being completely lost.
One thing that seems impossible to do with the plugin is to have variable &#8220;initial states&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://agilewebdevelopment.com/plugins/acts_as_state_machine">acts_as_state_machine</a> is a great plugin really useful when you want to add constraints and behavior to your model objects.</p>
<p><strong>Note</strong> : Those who don&#8217;t know what this plugin is all about should stop reading right there or risk being completely lost.</p>
<p>One thing that seems impossible to do with the plugin is to have variable &#8220;initial states&#8221; for an object. Say for example that you have a User model that needs to act as a state machine. New users have to fill up a signup form to gain access to the application. These new users will be &#8220;pending&#8221; until an administrator approve them (enabled) or refuse them (disabled)</p>
<pre lang="ruby">class User < ActiveRecord::Base
  acts_as_state_machine :initial => :pending
  state :pending
  state :enabled
  state :disabled

  event :enable do
    transitions :from => :pending, :to => :enabled
    transitions :from => :disabled, :to => :enabled
  end

  event :disable do
    transitions :from => :pending, :to => :disabled
    transitions :from => :enabled, :to => :disabled
  end
end</pre>
<p>So far so good. But what if an administrator can also create a new user? In this case we would&#8217;nt want the user to be &#8220;pending&#8221;, we want him to be &#8220;enabled&#8221; right away. </p>
<p>I experimented a similar scenario, so I tried a few things to bypass the initial state :</p>
<pre lang="ruby">#FAILED ATTEMPT #1
def create
  user = User.new(params[:user])
  user.state = :enabled
  user.save
end</pre>
<p>Too bad, so I tried this :</p>
<pre lang="ruby">#FAILED ATTEMPT #2
def create
  User.initial_state = :enabled
  user = User.new(params[:user])
  user.save
end</pre>
<p>Of course, the following worked :</p>
<pre lang="ruby">#SUCCESSFUL BUT SUCKY ATTEMPT
def create
  user = User.new(params[:user])
  user.save
  user.enable!
end</pre>
<p>Yuk&#8230; there had to be something better.</p>
<p>Finally, I learned that initial_state was an <em>inheritable attribute</em>. I didn&#8217;t know what those were all about so I did some googling. The only good explanation I found is <a href="http://gigavolt.net/blog/ruby-rails/inheritableAttributesInRails.writeback">this one</a>.</p>
<p>Anyway, I was able to override the initial state of my user object by doing this :</p>
<pre lang="ruby">#SUCCESSFUL ATTEMPT!
def create
  User.write_inheritable_attribute :initial_state, :enabled
  user = User.new(params[:user])
  user.save
end</pre>
<p>It&#8217;s not pretty I know, but at least it gets the job done. I wonder if the fact that you cannot &#8220;easily&#8221; change the initial state programmatically is a missing feature that should be added in a future version&#8230; or if it&#8217;s only my understanding of a &#8220;state machine&#8221; that sucks. Any thoughts?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubyfleebie.com/acts_as_state_machine-and-variable-initial-states/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

