<?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>Blog - ShiftEleven &#187; ruby</title>
	<atom:link href="http://shifteleven.com/articles/tag/ruby/feed" rel="self" type="application/rss+xml" />
	<link>http://shifteleven.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Sat, 19 Sep 2009 11:19:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0-alpha</generator>
		<item>
		<title>Useless Ruby Tricks: DATA and __END__</title>
		<link>http://shifteleven.com/articles/2009/02/09/useless-ruby-tricks-data-and-__end__</link>
		<comments>http://shifteleven.com/articles/2009/02/09/useless-ruby-tricks-data-and-__end__#comments</comments>
		<pubDate>Tue, 10 Feb 2009 03:20:17 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby off Rails]]></category>
		<category><![CDATA[DATA]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[__END__]]></category>

		<guid isPermaLink="false">http://shifteleven.com/?p=207</guid>
		<description><![CDATA[So maybe not totally useless certainly fun.  Normally, ruby scripts are finished when you reach the end of a file; however, this is not always the case.  You can end your script sooner by using the __END__ keyword in your script.  Once added, everything you type after that will not be parsed [...]]]></description>
			<content:encoded><![CDATA[<p>So maybe not totally useless certainly fun.  Normally, ruby scripts are finished when you reach the end of a file; however, this is not always the case.  You can end your script sooner by using the <code>__END__</code> keyword in your script.  Once added, everything you type after that will not be parsed by ruby.</p>
<p>So what?</p>
<p>Well, you can use the global variable <code>DATA</code> to get the contents of what you  wrote after the <code>__END__</code> block.  <code>DATA</code> is actually a <code>File</code> object to just that piece of text in your script.</p>
<p><span id="more-207"></span></p>
<p>How about a little sample to make things a little clearer?</p>
<pre class="ruby" title="code">#!/usr/bin/env ruby
%w(yaml pp).each { |dep| require dep }

obj = YAML::load(DATA)

pp obj

__END__
---
-
  name: Adam
  age: 28
  admin: true
-
  name: Maggie
  age: 28
  admin: false</pre>
<p>So with this, I was able to embed a little bit of YAML directly into my script.  I added the YAML after <code>__END__</code>.  <code>YAML::load</code> will accept a <code>File</code> object, so I just passed it <code>DATA</code> and now I have a reconstituted array.</p>
<p>Maybe that&#8217;s not the most practical use of this information; however, <a href="http://www.sinatrarb.com/">Sinatra</a> provides a really awesome use of this.  With Sinatra, you can create a whole web application that lives in one single, solitary ruby file.  Sinatra can use in-file templates.  In-file templates are added into the space after <code>__END__</code> where each view file is annotated with <code>@@view_name</code>.</p>
<pre class="ruby" title="code">require 'rubygems'
require 'sinatra'

get '/' do
  haml :index
end

__END__

@@ layout
%html
  = yield

@@ index
%div.title Hello world!!!!!</pre>
<p>Not bad for a useless trick!</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2009/02/09/useless-ruby-tricks-data-and-__end__/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Installing PostgreSQL on Leopard using MacPorts</title>
		<link>http://shifteleven.com/articles/2008/03/21/installing-postgresql-on-leopard-using-macports</link>
		<comments>http://shifteleven.com/articles/2008/03/21/installing-postgresql-on-leopard-using-macports#comments</comments>
		<pubDate>Sat, 22 Mar 2008 03:41:36 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[installation]]></category>
		<category><![CDATA[leopard]]></category>
		<category><![CDATA[macports]]></category>
		<category><![CDATA[pgadmin3]]></category>
		<category><![CDATA[postgresql]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://shifteleven.com/?p=43</guid>
		<description><![CDATA[I have always used MySQL but I wanted to give PostgreSQL a whirl.  This is what I did.

Prerequisites
Now I don&#8217;t want to go too deep into this, so I&#8217;m going to assume that if you are reading this, that you have the following installed

Mac OS Developer&#8217;s Tools
MacPorts
Ruby (comes with Leopard)

Ruby Gems (also comes with [...]]]></description>
			<content:encoded><![CDATA[<p>I have always used <a href="http://www.mysql.com/,">MySQL</a> but I wanted to give <a href="http://www.postgresql.org/">PostgreSQL</a> a whirl.  This is what I did.</p>
<p><span id="more-43"></span></p>
<h3>Prerequisites</h3>
<p>Now I don&#8217;t want to go too deep into this, so I&#8217;m going to assume that if you are reading this, that you have the following installed</p>
<ul>
<li><a href="http://developer.apple.com/tools/">Mac OS Developer&#8217;s Tools</a></li>
<li><a href="http://www.macports.org/install.php">MacPorts</a></li>
<li><a href="http://www.ruby-lang.org/">Ruby</a> (comes with Leopard)
<ul>
<li><a href="http://www.rubygems.org/">Ruby Gems</a> (also comes with Leopard)</li>
</ul>
</li>
</ul>
<p>So now that you have all of those dependencies out of the way, let&#8217;s get to installing us some PostgreSQL.</p>
<h3>PostgreSQL</h3>
<p>To install the database software, simply run the following command in <a href="http://www.apple.com/macosx/technology/unix.html">Terminal</a></p>
<pre>sudo port install \
  postgresql83 \
  postgresql83-server</pre>
<p>This will install the client and server needed for you to run this on your machine.  Now pay special attention to the installation script.  At the end of installation processes, macports will display a message for you that contains some commands for you to get started with.</p>
<h4>Configuration</h4>
<p>First, execute these lines of code.  This will setup a new database for you to play with</p>
<pre>sudo mkdir -p /opt/local/var/db/postgresql83/defaultdb
sudo chown postgres:postgres /opt/local/var/db/postgresql83/defaultdb
sudo su postgres -c '/opt/local/lib/postgresql83/bin/initdb -D /opt/local/var/db/postgresql83/defaultdb'</pre>
<h4>Start PostgreSQL Automatically</h4>
<p>By running the next command, you can have PostgreSQL lunch automatically so that it&#8217;s always available to you</p>
<pre>sudo launchctl load -w /Library/LaunchDaemons/org.macports.postgresql83-server.plist</pre>
<h3>pgAdmin III</h3>
<p><a href="http://www.pgadmin.org/">pgAdmin III</a> is a PostgreSQL management and administrations piece of software.  It&#8217;s a nice GUI to some things that you may find yourself wanting to do, like created databases and whatnot.  Installation of this is pretty cake.</p>
<pre>sudo port install pgAdmin3</pre>
<p>Upon completion of installation, you can find the application in <code>/Applications/MacPorts/pgAdmin3</code></p>
<h3>PostgreSQL Libraries for Ruby via Gems</h3>
<p>I have to admit, the previous installation steps were nothing to cry about; however, it was this step that made me want to put together this little walkthrough.</p>
<pre>sudo env ARCHFLAGS="-arch i386" \
  gem install postgres -- \
  --with-pgsql-lib=/opt/local/lib/postgresql83 \
  --with-pgsql-include=/opt/local/include/postgresql83</pre>
<p>That&#8217;s not exactly your everyday <code>gem install</code> command.  For one, the environment variable <code>ARCHFLAGS</code> has to be set.  Secondly, the <code>gem</code> command needs to know where the PostgreSQL  libraries and include headers are so that it can compile.  Looking back, it&#8217;s actually quite easy to copy and paste that command, it just took me a while to find out exactly what I needed to make it work.</p>
<h3>Fin</h3>
<p>Well, I hope that helps anyone looking to install and setup PostgreSQL in Leopard.  Until next time&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2008/03/21/installing-postgresql-on-leopard-using-macports/feed</wfw:commentRss>
		<slash:comments>42</slash:comments>
		</item>
		<item>
		<title>Forget About Little Old CGI</title>
		<link>http://shifteleven.com/articles/2008/03/17/forget-about-little-old-cgi</link>
		<comments>http://shifteleven.com/articles/2008/03/17/forget-about-little-old-cgi#comments</comments>
		<pubDate>Tue, 18 Mar 2008 00:53:31 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby off Rails]]></category>
		<category><![CDATA[cgi]]></category>
		<category><![CDATA[rack]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://shifteleven.com/?p=41</guid>
		<description><![CDATA[Maybe someone may have told you to use ruby and CGI together, but I think that person has a screw loose.  I mean, come on.  Everyone knows that what you really need to use is Rack

Why Rack
Well for one, it&#8217;s light weight.  So if you want to deploy your ruby script using [...]]]></description>
			<content:encoded><![CDATA[<p>Maybe someone may have told you to use <a href="http://shifteleven.com/articles/2008/03/13/dont-forget-about-little-old-cgi">ruby and CGI</a> together, but I think that person has a screw loose.  I mean, come on.  Everyone knows that what you really need to use is <a href="http://rack.rubyforge.org/">Rack</a></p>
<p><span id="more-41"></span></p>
<h3>Why Rack</h3>
<p>Well for one, it&#8217;s light weight.  So if you want to deploy your ruby script using CGI, you can do that with Rack.</p>
<p>But let&#8217;s say, you want to your script to Mongrel, or WEBRick, or FCGI; you can do that too, and with very few changes to your script.  That&#8217;s because Rack abstracts all the boilerplate code you would need to work with those servers and bundles it up into a nice interface for you to use.</p>
<p>Oh, and the code to use Rack is very easy.  Here&#8217;s an example of a Rack app for you:</p>
<h3>Examples</h3>
<pre class="ruby" title="code">%w(rubygems rack haml).each { |dep| require dep }

class IndexPage
  def call(env)
    haml_engine = Haml::Engine.new(File.read('../templates/index.haml'))
    [
      200,
      { "Content-Type" =&gt; "text/html" },
      haml_engine.render(Object.new, {})
    ]
  end
end

Rack::Handler::CGI.run(IndexPage.new)</pre>
<p>The secret behind Rack is that it will run any ruby object that has a <code>call</code> method and pass in the environment variables to it.  In that environment variable, you will find things like HTTP_HOST, or QUERY_STRING, and the like.</p>
<p>If you wanted to have this script now work with WEBRick, no problem.</p>
<pre class="ruby" title="code"># Same code as above, with just a little tweak to the last line

Rack::Handler::WEBRick.run(IndexPage.new, :Port =&gt; 3000)</pre>
<p>Tada!  So now you can run a test server without worrying about setting up Apache or Lighttpd.</p>
<h3>More Goodness</h3>
<p>To make your life easier, Rack also comes with a set of middleware for you to use.  Say you have an error in your application.  Perhaps you would like to see that error formatted nicely in your browser.  You can enable <code>Rack::ShowExceptions</code>.  Perhaps you would like the code you have to be reloaded from the server whenever it changes, like when you&#8217;re developing your application, then you can use <code>Rack::Reloader</code>.</p>
<p>To use those options, you can write your Rack handler like</p>
<pre class="ruby" title="code">app = Rack::Builder.new do
  use Rack::CommonLogger  # apache-like logger
  use Rack::ShowExceptions
  use Rack::Reloader
  use Rack::ShowStatus  # create default pages for common HTTP error codes
  use Rack::Lint  #ensures all applications behave validly
  run Index.new
end
Rack::Handler::WEBRick.run(app, :Port =&gt; 3000)</pre>
<p>There&#8217;s plenty of magic going on with Rack; A magic that does not sacrifice speed and/or flexibility.  I would highly recommend giving Rack a look into the next time you want to write a simple web page.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2008/03/17/forget-about-little-old-cgi/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Forget About Little Old CGI</title>
		<link>http://shifteleven.com/articles/2008/03/13/dont-forget-about-little-old-cgi</link>
		<comments>http://shifteleven.com/articles/2008/03/13/dont-forget-about-little-old-cgi#comments</comments>
		<pubDate>Fri, 14 Mar 2008 03:36:46 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby off Rails]]></category>
		<category><![CDATA[cgi]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://shifteleven.com/?p=40</guid>
		<description><![CDATA[Rails is great and all, but sometimes it can be just a little too much and you just need to set up a few pages, not the next big app.  Fear not, there is still tool in the ruby tool box at your disposal: the CGI library CGI is fast and lean and still [...]]]></description>
			<content:encoded><![CDATA[<p>Rails is great and all, but sometimes it can be just a little too much and you just need to set up a few pages, not the next big app.  Fear not, there is still tool in the ruby tool box at your disposal: <a href="http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/index.html.">the CGI library</a> CGI is fast and lean and still can be used will all of your favorite friends, like <a href="http://haml.hamptoncatlin.com/">HAML</a></p>
<p><span id="more-40"></span></p>
<p>Since you&#8217;re using CGI, you don&#8217;t _have_ to worry about setting up FCGI, or Mongrel.  You can use <a href="http://www.modruby.net/en/">mod_ruby</a> if you&#8217;re using Apache or cgi with Lighttpd.</p>
<p>So now that servers are out of the way, time for some code.</p>
<p>I mentioned that you don&#8217;t have to give up HAML. So for that, I propose this little directory structure.</p>
<pre title="code">mysite/
   |- templates/
   `- public/</pre>
<p>Hopefully you guessed that <code>templates</code> contains your HAML templates and <code>public</code> is the webroot for your site.  Now in your <code>public</code> directory, create an <code>index.rb</code> file, and perhaps it could somewhat look like:</p>
<pre class="ruby" title="code">require 'rubygems'
require 'haml'
require 'cgi'

# A Hash for all of the variables we want to send to HAML
model = {}

# Why not get the time
model[:time] = Time.now

cgi = CGI.new

# Set up the template
haml_engine = Haml::Engine.new(File.read('../templates/index.haml'))

# Render out the HTML
cgi.out { haml_engine.render(Object.new, model) }</pre>
<p>And there&#8217;s the tedious code.  There are some interesting pieces to notice.  For one, when calling cgi.out, that sends out the proper headers out to the browser *(very important)*.  Also, this could probably be wrapped up into a nice function to reduce the strain of repeating one&#8217;s self.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2008/03/13/dont-forget-about-little-old-cgi/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Blocks and Helpers, a Lovely Combination</title>
		<link>http://shifteleven.com/articles/2007/01/22/blocks-and-helpers-a-lovely-combination</link>
		<comments>http://shifteleven.com/articles/2007/01/22/blocks-and-helpers-a-lovely-combination#comments</comments>
		<pubDate>Tue, 23 Jan 2007 01:49:36 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[block]]></category>
		<category><![CDATA[DRY]]></category>
		<category><![CDATA[helper]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/?p=25</guid>
		<description><![CDATA[Blocks rock and I couldn&#8217;t agree more.  The functional programming aspect of ruby has started to interest me more and more.  Blocks are used all over the place, with respond_to, collect, returning and ActionView::Helpers::FormHelper#form_for.
Sometimes, a design requires a little extra markup, perhaps something to get that rounded corner to work or what-have you. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://weblog.jamisbuck.org/2007/1/19/blocks-rock">Blocks rock</a> and I couldn&#8217;t agree more.  The <a href="http://tech.rufy.com/2006/11/functional-programming-in-ruby.html">functional programming aspect of ruby</a> has started to interest me more and more.  Blocks are used all over the place, with <a href="http://api.rubyonrails.com/classes/ActionController/MimeResponds/InstanceMethods.html#M000080,"><code>respond_to</code></a>, <a href="http://www.ruby-doc.org/core/classes/Enumerable.html#M003163,"><code>collect</code></a>, <a href="http://errtheblog.com/post/29,"><code>returning</code></a> and <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/FormHelper.html#M000491."><code>ActionView::Helpers::FormHelper#form_for</code></a><code>.</code></p>
<p>Sometimes, a design requires a little extra markup, perhaps something to get that rounded corner to work or what-have you.  Now let&#8217;s say this piece of code requires certain classes, a certain kind of structure, including a tile, and has to be used in many places, something like a sidebar piece.  Instead of copying and pasting this structure over and over, you can use a helper to make you life easier, and if you combine it with a block, it will just feel even more painless.</p>
<p><span id="more-25"></span></p>
<h3>The Setup</h3>
<pre class="html" title="code">&lt;div class="sidebar"&gt;
  &lt;div class="bottom"&gt;
    &lt;h3&gt;Title&lt;/h3&gt;
    &lt;div class="body"&gt;
      &lt;p&gt;Some Content&lt;/p&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
<p>There are two elements which must change; the title and the contents of the body.  The title should simply be just some text that goes in between the <code>h3</code> tag.  The contents of the body could be anything, in this case, it is the paragraph tag and everything inside.</p>
<h3>Creating a Helper without a Block</h3>
<p>Since we have these two varying things, we could create a helper method to encapsulate our structure.  The first parameter of the helper will be the title while the second parameter will be the contents of the body.</p>
<pre class="ruby" title="code">def sidebar(title, body)
  content_tag(
    'div',
    content_tag(
      'div',
      content_tag('h3', title) + content_tag('div', body, :class =&gt; 'body'),
      :class =&gt; 'bottom'
    ),
    :class =&gt; 'sidebar'
  )
end</pre>
<p>That looks pretty easy.  Now let&#8217;s look at the interface for this helper</p>
<pre class="html" title="code">&lt;%= sidebar('Hello World',
  '&lt;p&gt;It is one of these "Hello World" things again.&lt;/p&gt;') %&gt;</pre>
<p>Not too shabby, but what if we wanted to do an unordered list?</p>
<pre class="ruby" title="code">&lt;%= sidebar(
  'Hello World',
  '&lt;ul&gt;' +
    '&lt;li&gt;Item&lt;/li&gt;' +
    '&lt;li&gt;Item&lt;/li&gt;' +
    '&lt;li&gt;Item&lt;/li&gt;' +
  '&lt;/ul&gt;'
) %&gt;</pre>
<p>This feels pretty clunky and <a href="http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/">ERB</a> is completely ignored.  Instead of this procedural way of thinking, why not see what a block can do for us?</p>
<h3>Creating a Helper +with+ a Block</h3>
<p>For this to work, we will still need the first parameter to be the title, but the body will be passed in as a block to be processed from within our helper.  The block we create will be ERB code, this will feel more natural to the person who has to implement the code.  The magic to get this done comes from the <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/TextHelper.html#M000611"><code>concat</code></a> method of <code>ActionView::Helpers::TextHelper</code> module.</p>
<pre class="ruby" title="code">def sidebar(title, &amp;block)
  raise ArgumentError, "Missing block" unless block_given?

  start = &lt;&lt;-END
    &lt;div class="sidebar"&gt;
      &lt;div class="bottom"&gt;
        &lt;h3&gt;#{title}&lt;/h3&gt;
        &lt;div class="body"&gt;
  END
  concat(start, block.binding)

  block.call

  end = &lt;&lt;-END
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  END
  concat(end, block.binding)

end</pre>
<p>This may look slightly odd, but I assure you, the interface makes up for it.</p>
<pre class="html" title="code">&lt;% sidebar('Hello World') do %&gt;
  &lt;p&gt;And now back to the way I was doing things before&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;Item&lt;/li&gt;
    &lt;li&gt;Item&lt;/li&gt;
    &lt;li&gt;Item&lt;/li&gt;
  &lt;/ul&gt;
&lt;% end %&gt;</pre>
<h3>The Benefits</h3>
<ul>
<li>The implementation code is more readable</li>
<li>It gives you one place to make your common edits</li>
<li>It keeps your code <a href="http://www.artima.com/intv/dry.html">DRY(don&#8217;t repeat yourself)</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2007/01/22/blocks-and-helpers-a-lovely-combination/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>I heart Ruby: Metaprogramming</title>
		<link>http://shifteleven.com/articles/2006/09/09/i-heart-ruby-metaprogramming</link>
		<comments>http://shifteleven.com/articles/2006/09/09/i-heart-ruby-metaprogramming#comments</comments>
		<pubDate>Sat, 09 Sep 2006 21:04:29 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/articles/2006/09/09/i-heart-ruby-metaprogramming</guid>
		<description><![CDATA[So today I had an interesting problem.  For whatever the reason, I wanted to have a class automagically be created.  It was going to be a helper model, and I didn&#8217;t feel like having umteen classes that all did the same thing, just had different names for different tables.  My solution: use [...]]]></description>
			<content:encoded><![CDATA[<p>So today I had an interesting problem.  For whatever the reason, I wanted to have a class automagically be created.  It was going to be a helper model, and I didn&#8217;t feel like having <a href="http://www.thefreedictionary.com/umteen">umteen</a> classes that all did the same thing, just had different names for different tables.  My solution: use the power of ruby and <a href="http://poignantguide.net/ruby/chapter-6.html.">metaprogramming</a></p>
<pre class="ruby" title="code">def create_new_active_record_model(class_name)
  klass = Class.new(ActiveRecord::Base) do
    belongs_to :old, :class_name =&gt; class_name
    def some_method_you_want
      "something"
    end
  end
  Object.const_set "#{class_name}Target", klass
end</pre>
<p>I know that some of this could have been encapsulated in a <a href="http://wiki.rubyonrails.org/rails/pages/UnderstandingPolymorphicAssociations,">polymorphic association</a> but this allows you to do something beyond just keeping everything in one table, like with polymorphic associations.</p>
<p><span id="more-8"></span></p>
<p>This could be useful for creating something like a garbage collector.  After something is deleted, it could go to this garbage heap.  Having a lot of  models would mean having a lot of garbage collection models.  The garbage collection models could easily be abstracted enough so that one doesn&#8217;t have to worry about the man behind the curtain.</p>
<p>In some ways it would be better than an <a href="http://ar-paranoid.rubyforge.org/."><code>acts_as_paranoid</code></a> For large tables there won&#8217;t be data cluttering it up.  Since all of the data is happening on live data, keeping the dirty out can help performance.  Also, when I used <code>acts_as_paranoid</code>, I had to make sure that I put conditionals on all of my <code>belongs_to</code> and <code>has_many</code> statements; that way when I do something like <code>user.posts</code>,I wont get deleted posts.</p>
<p>If I had to compare it to something that already exists, it&#8217;s like an <a href="http://ar-versioned.rubyforge.org,"><code>acts_as_versioned</code></a> but it only cares when something is deleted.</p>
<p>When I get some more time, I will work on creating a <code>acts_as_trashable</code> or something of that nature :)</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/09/09/i-heart-ruby-metaprogramming/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Looking towards Rails 1.2 with CRUD</title>
		<link>http://shifteleven.com/articles/2006/08/29/looking-towards-rails-12-with-crud</link>
		<comments>http://shifteleven.com/articles/2006/08/29/looking-towards-rails-12-with-crud#comments</comments>
		<pubDate>Wed, 30 Aug 2006 01:28:42 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[crud]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[rubyconf]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/articles/2006/08/29/4</guid>
		<description><![CDATA[A couple of months ago, I was shown the article that DHH(David Heinemeier Hannson) wrote after he gave his presentation at RailsConf 2006.  I looked at it then and kind of shrugged it off, mainly because I really didn&#8217;t know what the presentation was really about.
Tonight I found video of that presentation and I [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of months ago, I was shown the <a href="http://www.loudthinking.com/arc/000593.html">article</a> that DHH(David Heinemeier Hannson) wrote after he gave his presentation at RailsConf 2006.  I looked at it then and kind of shrugged it off, mainly because I really didn&#8217;t know what the <a href="http://www.loudthinking.com/lt-files/worldofresources.pdf">presentation</a> was really about.</p>
<p>Tonight I found <a href="http://blog.scribestudio.com/articles/2006/07/09/david-heinemeier-hansson-railsconf-2006-keynote-address">video</a> of that presentation and I got excited about CRUD(Create, Read, Update, Delete).  It pointed out that I&#8217;ve been making some controllers a little bloated.  I have coupled much functionality into one controller; when looking back, I clearly could have separated out some functionality.</p>
<p><span id="more-4"></span></p>
<h3>Learning to love <code>has_many :through</code> even more with CRUD</h3>
<p>One of the points about this is that the coupling often happens when you have models that are joined by a table, like in a HABTM(has_many_and_belongs_to) relationship.   The table that joins the two other tables as an amorphous name, whose role changes depending on which side of the join table you are looking. <code>has_many :through</code> fixes this ambiguity as it gives a name to a new model, and thus a new domain to think about creating clean uses of CRUD.  An example will make this much clearer.</p>
<h4>The non-CRUD way</h4>
<pre class="ruby" title="code">class Author &lt; ActiveRecord::Base
  has_and_belongs_to_many :books
end

class Book &lt; ActiveRecord::Base
  has_and_belongs_to_many :authors
end</pre>
<p>Let&#8217;s say I have a AuthorController and we want to add books to an author, or remove a book from an author, we could write the following.</p>
<pre class="ruby" title="code">class AuthorController &lt; ApplicationController
  def add_book
  end

  def remove_book
  end
end</pre>
<p>This doesn&#8217;t seem that harmless, but what if we wanted to add authors to a book?</p>
<pre class="ruby" title="code">class BookController &lt; ApplicationController
  def add_author
  end

  def remove_author
  end
end</pre>
<p>This does not follow the ways of DRY(Don&#8217;t Repeat Yourself), because depending on which side of the coin you are looking at, you have two different ways to accomplish pretty much the same thing.</p>
<h4>Enter <code>has_many :through</code></h4>
<p>DHH points out that if we can identify the link between Authors and Books, there will be a new a less ambiguous and more elegant way to think about this issue.  The link to identify here is Authorship.  Now let&#8217;s change our models some.</p>
<pre class="ruby" title="code">class Author &lt; ActiveRecord::Base
  has_many :authorships
  has_many :books, :through =&gt; :authorships
end

class Authorship &lt; ActiveRecord::Base
  belongs_to :author
  belongs_to :book
end

class Book &lt; ActiveRecord::Base
  has_many :authorships
  has_many :authors, :through =&gt; :authorships
end</pre>
<p>Because the link has been identified, a controller can be created with the ideals of CRUD put right into place.</p>
<pre class="ruby" title="code">class AuthorshipController &lt; ApplicationController
  def create
    #Authorship.create(:author_id =&gt; params[:author_id], :book =&gt; params[:book_id])
  end

  def destroy
  end
end</pre>
<p>Everything is right with the world again</p>
<h3>POST, GET, PUT, DELETE</h3>
<p>The other big thing that was mentioned was mapping CRUD functionality to HTTP(hypertext transfer protocol) method definitions: POST, GET, PUT, and DELETE respectively.  The HTTP method acts as the verb for what the controller should do.  Here is the basic outline, the comments are how things fit into the lovely world the the HTTP methods as verbs:</p>
<pre class="ruby" title="code">class SomethingController &lt; ApplicationController

  # POST /something
  def create
  end

  # GET /something/1
  def show
  end

  # PUT /something/1
  def update
  end

  # DELETE /people/1
  def destroy
  end

end</pre>
<p>Since browsers don&#8217;t use PUT or DELETE, Rails has a hack for this; it&#8217;s going to send hidden fields with the actions so that the mappings know how to handle everything.  Those methods aren&#8217;t the only ones that are apart of the CRUD; there are other ones that are common to most controllers:</p>
<pre class="ruby" title="code">class SomethingController &lt; ApplicationController

  # GET /something
  def index
  end

  # GET /something;new
  def new
  end

  # GET /something/1;edit
  def edit
  end

end</pre>
<p><code>index</code> is responsible for listing all of the somethings, while <code>new</code> and <code>edit</code> are how users first start their journey to creating or updating something.</p>
<p>Clarity in this layout isn&#8217;t the other reason to use this.  The other reason Rails is going to be embracing <a href="http://www.xfront.com/REST-Web-Services.html">REST(Representational State Transfer)</a> ideals into the way Rails will route your URLs.  More on this later when I dive deeper into it.</p>
<p>Because of this presentation, I&#8217;m thinking about how I&#8217;m doing my controllers.  I usually don&#8217;t have this type of setup, but I am definitely going to start using it.  From now on, I will not be afraid do use the command <code>script/generate controller Something index new create show edit update destroy</code> and start to think about controllers from a CRUD perspective rather than creating more monolithic controllers, and to be ready for when Rails 1.2 comes in full effect.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/08/29/looking-towards-rails-12-with-crud/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
