<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.2" -->
<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/"
	>

<channel>
	<title>matt-beedle.com</title>
	<link>http://matt-beedle.com</link>
	<description></description>
	<pubDate>Fri, 20 Jun 2008 10:18:25 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.2</generator>
	<language>en</language>
			<item>
		<title>Rails Developer Needed!</title>
		<link>http://matt-beedle.com/2008/06/20/rails-developer-needed/</link>
		<comments>http://matt-beedle.com/2008/06/20/rails-developer-needed/#comments</comments>
		<pubDate>Fri, 20 Jun 2008 09:54:13 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2008/06/20/rails-developer-needed/</guid>
		<description><![CDATA[Well, it&#8217;s been about 9 months since I last posted.  Time&#8217;s been a little sparse of late.  Today though, I have a good work related reason to spend 5 minutes blogging:  We need a Ruby on Rails developer ASAP for a 6 month rolling contract to assist me at a startup in [...]]]></description>
			<content:encoded><![CDATA[<p>Well, it&#8217;s been about 9 months since I last posted.  Time&#8217;s been a little sparse of late.  Today though, I have a good work related reason to spend 5 minutes blogging:  <strong>We need a Ruby on Rails developer ASAP</strong> for a 6 month rolling contract to assist me at a startup in sunny Barcelona.  I moved here 4 weeks ago, and don&#8217;t know any Ruby on Rails developers locally.  Ideally I would like someone on site, but if you are good, then we can definitely come to some remote working agreement.</p>
<p>The site&#8217;s in a bit of a mess at the moment (the original guy had a build it quick and hack it around style of coding), but I have now begun to set up rspec tests, a cruise control server and Git version control.  So if you would like to work in a fun young environment, in a sunny country next to the beach, using Ruby on Rails, Git, haml/sass, cruise control, and test driven development, and get a real say in the business technical direction, then please drop me a mail.  No agents though please. <a href="http://jobs.rubynow.com/jobs/show/2303">Here&#8217;s the job description</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2008/06/20/rails-developer-needed/feed/</wfw:commentRss>
		</item>
		<item>
		<title>rspec on rails, LocalJumpError - no block given</title>
		<link>http://matt-beedle.com/2007/09/24/rspec-on-rails-localjumperror-no-block-given/</link>
		<comments>http://matt-beedle.com/2007/09/24/rspec-on-rails-localjumperror-no-block-given/#comments</comments>
		<pubDate>Mon, 24 Sep 2007 16:41:49 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2007/09/24/rspec-on-rails-localjumperror-no-block-given/</guid>
		<description><![CDATA[Quite frequently in rails I find myself saying something like:

def show
  @photo = User.find(params[:user_id]).photos.find(params[:id])
end

Pretty simple right&#8230;
But it can be the cause of headaches when trying to write rspec tests.  Writing the following test:

describe PhotosController, &#8216;handling GET /users/1/photos/2.png&#8217; do
  before(:each) do
    @photo = mock_model(Photo)
    @user = mock_model(User, [...]]]></description>
			<content:encoded><![CDATA[<p>Quite frequently in rails I find myself saying something like:</p>
<pre><code class="ruby">
<span class="keywords">def</span> show
  @photo = User.find(params[<span class="symbol">:user_id</span>]).photos.find(params[<span class="symbol">:id</span>])
<span class="keywords">end</span>
</code></pre>
<p>Pretty simple right&#8230;</p>
<p>But it can be the cause of headaches when trying to write rspec tests.  Writing the following test:</p>
<pre><code>
<span class="keywords">describe</span> PhotosController, <span class="string">&#8216;handling GET /users/1/photos/2.png&#8217;</span> <span class="keywords">do</span>
  <span class="keywords">before</span>(<span class="symbol">:each</span>) <span class="keywords">do</span>
    @photo = mock_model(<span class="erb">Photo</span>)
    @user = mock_model(<span class="erb">User</span>, <span class="symbol">:photos</span> => [@photo])
    [@photo].stub!(<span class="symbol">:find</span>).and_return(@photo)
    User.stub!(<span class="symbol">:find</span>).and_return(@user)
  <span class="keywords">end</span>

  <span class="keywords">def</span> <span class="defname">do_get</span>
    get <span class="string">&#8217;show&#8217;</span>, <span class="symbol">:user_id</span> => 1, <span class="symbol">:id</span> => 2, <span class="symbol">:format</span> => <span class="string">&#8216;png&#8217;</span>
  <span class="keywords">end</span>

  <span class="keywords">it</span> <span class="string">&#8220;should find the specified user&#8221;</span> do
    <span class="erb">User</span>.should_receive(<span class="symbol">:find</span>).once.with(<span class="string">&#8216;1&#8242;</span>).and_return(@user)
    <span class="defname">do_get</span>
  <span class="keywords">end</span>

  <span class="keywords">it</span> <span class="string">&#8220;should find the found users photos&#8221;</span> <span class="keywords">do</span>
    @user.should_receive(<span class="symbol">:properties</span>).once.and_return([@photo])
    <span class="defname">do_get</span>
  <span class="keywords">end</span>

  <span class="keywords">it</span> <span class="string">&#8220;should find the specified photo from within the found photos&#8221;</span> <span class="keywords">do</span>
    [@photo].should_receive(<span class="symbol">:find</span>).once.with(<span class="string">&#8216;2&#8242;</span>).and_return(@photo)
    <span class="defname">do_get</span>
  <span class="keywords">end</span>
<span class="keywords">end</span>
</code></pre>
<p>Will result in the following errors:<br />
<code>
<pre>
LocalJumpError in 'PhotosControllerhandling GET /users/1/photos/2.png should find the specified user'
no block given
LocalJumpError in 'PhotosControllerhandling GET /users/1/photos/2.png should find the found users photos'
no block given
LocalJumpError in 'PhotosControllerhandling GET /users/1/photos/2.png should find the specified photo from within the found photos'
no block given
</pre>
<p></code></p>
<p>The cause of the problem is this.  When rspec runs it is calling the Ruby Enumerable#find on an array of one object [@photo].  Enumerable#find expects a block.  In the rails code, ActiveRecord::Base::find is being called which is really doing a scoped find for all photos belonging to the user.  The solution is to stub the find method on the photos array in the before block of your rspec tests.  Here is the working test:</p>
<pre><code>
<span class="keywords">describe</span> PhotosController, <span class="string">&#8216;handling GET /users/1/photos/2.png&#8217;</span> <span class="keywords">do</span>
  <span class="keywords">before</span>(<span class="symbol">:each</span>) <span class="keywords">do</span>
    @photo = mock_model(<span class="erb">Photo</span>)
    <strong>@photos = [@photo]
    @photos.stub!(<span class="symbol">:find</span>).and_return(@photo)</strong>
    @user = mock_model(<span class="erb">User</span>, <span class="symbol">:photos</span> => @photos)
    <span class="erb">User</span>.stub!(<span class="symbol">:find</span>).and_return(@user)
  <span class="keywords">end</span>

  <span class="keywords">def</span> <span class="defname">do_get</span>
    get <span class="string">&#8217;show&#8217;</span>, <span class="symbol">:user_id</span> => 1, <span class="symbol">:id</span> => 2, <span class="symbol">:format</span> => <span class="string">&#8216;png&#8217;</span>
  <span class="keywords">end</span>

  <span class="keywords">it</span> <span class="string">&#8220;should find the specified user&#8221;</span> <span class="keywords">do</span>
    <span class="erb">User</span>.should_receive(<span class="symbol">:find</span>).once.with(<span class="string">&#8216;1&#8242;</span>).and_return(@user)
    <span class="defname">do_get</span>
  <span class="keywords">end</span>

  <span class="keywords">it</span> <span class="string">&#8220;should find the found users photos&#8221;</span> <span class="keywords">do</span>
    <strong>@user.should_receive(<span class="symbol">:properties</span>).once.and_return(@photos)</strong>
    <span class="defname">do_get</span>
  <span class="keywords">end</span>

  <span class="keywords">it</span> <span class="string">&#8220;should find the specified photo from within the found photos&#8221;</span> <span class="keywords">do</span>
    <strong>@photos.should_receive(<span class="symbol">:find</span>).once.with(<span class="string">&#8216;2&#8242;</span>).and_return(@photo)</strong>
    <span class="defname">do_get</span>
  <span class="keywords">end</span>
<span class="keywords">end</span>
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2007/09/24/rspec-on-rails-localjumperror-no-block-given/feed/</wfw:commentRss>
		</item>
		<item>
		<title>best-mobile-phones.org attempt 2!</title>
		<link>http://matt-beedle.com/2007/08/21/best-mobile-phonesorg-attempt-2/</link>
		<comments>http://matt-beedle.com/2007/08/21/best-mobile-phonesorg-attempt-2/#comments</comments>
		<pubDate>Tue, 21 Aug 2007 11:21:32 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[SEO (Search Engine Optimisation)]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2007/08/21/best-mobile-phonesorg-attempt-2/</guid>
		<description><![CDATA[I have finally gotten around to re-writing the first rails site I ever wrote.  So here it is http://www.best-mobile-phones.org.uk, the new and improved best mobile phones.  The original was just a simple DB, and literally everything was using page caching.  I had used out of the box scaffolding to edit the db, [...]]]></description>
			<content:encoded><![CDATA[<p>I have finally gotten around to re-writing the first rails site I ever wrote.  So here it is <a href="http://www.best-mobile-phones.org.uk">http://www.best-mobile-phones.org.uk</a>, the new and improved best mobile phones.  The original was just a simple DB, and literally everything was using page caching.  I had used out of the box scaffolding to edit the db, and whenever a user submitted a review, a cache_sweeper would clear the required pages from the cache.</p>
<p>The new site is built almost completely using REST.  All phones lists are paginated using the <a href="http://errtheblog.com/post/4791">will_paginate</a> plugin, although I have not implemented the AJAX version yet.  All the images are stored in the DB, and cached on the server when requested.  I&#8217;ve also built a sweet CMS which allows me to edit almost anything on the site once logged in.  There are sweepers set up for all of the data so any caches affected by the CMS are automatically expired.  Finally, I also decided it was time to learn some web2.0 CSS! So I got my GIMP out, made a &#8220;Beta&#8221; badge, and curved the edges of any box I saw!  So there it is, please go take a look, find some bugs, give me some feedback, buy a phone. End advertisement!</p>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2007/08/21/best-mobile-phonesorg-attempt-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Custom REST routes</title>
		<link>http://matt-beedle.com/2007/07/17/custom-rest-routes/</link>
		<comments>http://matt-beedle.com/2007/07/17/custom-rest-routes/#comments</comments>
		<pubDate>Tue, 17 Jul 2007 11:27:48 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2007/07/17/custom-rest-routes/</guid>
		<description><![CDATA[When developing rails applications using REST, all controllers have only seven actions (index, show, new, create, edit, update and destroy).  Occasionally there is a need for additional custom actions.  They can be added very simply in config/routes.rb.  For example, in part of an application showing a list of venues,  you may [...]]]></description>
			<content:encoded><![CDATA[<p>When developing rails applications using REST, all controllers have only seven actions (index, show, new, create, edit, update and destroy).  Occasionally there is a need for additional custom actions.  They can be added very simply in config/routes.rb.  For example, in part of an application showing a list of venues,  you may want to list only venues which have not closed down, and you may want to mark a venue as closed_down.</p>
<p>Your initial config/routes.rb setup would look something like this:</p>
<pre>
  ActionController::Routing::Routes.draw do |map|
    map.resources :venues
  end
</pre>
<p>To list all venues that are closed down you would first need to add the following action to your venue_controller.rb:</p>
<pre>
  def closed
    @venues = Venue.find(:all, :conditions => ['closed_down = ?', true])
  end
</pre>
<p>However, trying to navigate to this action will result in a routing error.  To fix this, you will need to amend routes.rb:</p>
<pre>
  ActionController::Routing::Routes.draw do |map|
    map.resources :venues, :collection => {:closed => :get}
  end
</pre>
<p>The collection hash is used to specify actions which reference collections of objects instead of actions which reference one object.  In this case the closed action is referencing a collection of venues.  Inside the hash :closed is mapped to a GET request.  This will also automatically create a named route: closed_venues_path.  Cool!</p>
<p>So that&#8217;s working.  Now to be able to mark a venue as closed_down.<br />
In your venues_controller.rb you would add the following action:</p>
<pre>
def mark_closed_down
  @venue = Venue.find(params[:id])
  @venue.update_attribute :closed_down, true
  redirect_to closed_venues_path
end
</pre>
<p>However, trying to navigate to this action will currently throw an error, as following the current RESTful setup the application will try to render the show action, which will try to find a venue with id => &#8216;mark_closed_down&#8217;.</p>
<p>To fix this you need to make the following change to your routes.rb file:</p>
<pre>
  ActionController::Routing::Routes.draw do |map|
    map.resources :venues, :collection => {:closed => :get}, :member => { :mark_closed_down => :put }
  end
</pre>
<p>The member hash is used to specify actions that reference one object in particular.  In this case mark_closed_down is referencing one venue.  Inside the hash :mark_closed_down is mapped to a PUT request.  This also gives you a named route: mark_closed_down_venue_path(venue).  Thats it!</p>
<p>You can add as many custom routes as you like to each controller, but you should do so with caution.  If you find yourself needing lots of them it probably means that you have missed a model, or that you should create another controller.  Each controller maps one to one with a resource, but not necessarily with a model.  In this case, for example, it would be possible to map another resource in routes.rb maybe called closed_down_venues:</p>
<pre>
map.resources :closed_down_venues
</pre>
<p>Then create a closed_down_venues controller with:</p>
<pre>
script/generate controller closed_down_venues
</pre>
<p>The index action would then be the list of closed venues, and the update action would be the mark_closed_down action.</p>
<p>I hope this is all clear.  Please add a comment if not, and I will do my best to clarify&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2007/07/17/custom-rest-routes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Asshole driven development!</title>
		<link>http://matt-beedle.com/2007/06/22/asshole-driven-development/</link>
		<comments>http://matt-beedle.com/2007/06/22/asshole-driven-development/#comments</comments>
		<pubDate>Fri, 22 Jun 2007 07:50:58 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[Life]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2007/06/22/asshole-driven-development/</guid>
		<description><![CDATA[This link was sent around the office a couple of days ago, and I just couldn&#8217;t resist posting it.  Very amusing.  I&#8217;ve definitely witnessed a some of these methodologies in practice&#8230; http://www.scottberkun.com/blog/2007/asshole-driven-development/
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.scottberkun.com/blog/2007/asshole-driven-development/">This link</a> was sent around the office a couple of days ago, and I just couldn&#8217;t resist posting it.  Very amusing.  I&#8217;ve definitely witnessed a some of these methodologies in practice&#8230; <a href="http://www.scottberkun.com/blog/2007/asshole-driven-development/">http://www.scottberkun.com/blog/2007/asshole-driven-development/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2007/06/22/asshole-driven-development/feed/</wfw:commentRss>
		</item>
		<item>
		<title>acts_as_emailable</title>
		<link>http://matt-beedle.com/2007/06/05/acts_as_emailable/</link>
		<comments>http://matt-beedle.com/2007/06/05/acts_as_emailable/#comments</comments>
		<pubDate>Tue, 05 Jun 2007 20:33:11 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2007/06/05/acts_as_emailable/</guid>
		<description><![CDATA[Quite often when building a site, I find that it would be nice if users could email each other within the site.  In my previous post I explained how to set up the models and relationships for this.  Today I&#8217;ve gone one step further and packaged them up into a plugin: acts_as_emailable.  [...]]]></description>
			<content:encoded><![CDATA[<p>Quite often when building a site, I find that it would be nice if users could email each other within the site.  In my <a href="http://matt-beedle.com/2007/06/02/how-to-model-an-internal-emailing-system-using-self-referential-has_many-through-associations/">previous post</a> I explained how to set up the models and relationships for this.  Today I&#8217;ve gone one step further and packaged them up into a plugin: acts_as_emailable.  Here is how to use it:</p>
<p>Setup<br />
=====<br />
First up you need to install the plugin.  This can be done like so:</p>
<pre><code>script/plugin install svn://matt-beedle.com:3396/acts_as_emailable
</code></pre>
<p>Then generate the model and migration for the emails table.</p>
<pre><code>script/generate acts_as_emailable_model Email
rake db:migrate
</code></pre>
<p>Now you are ready to go.  Just add the following line of code to your User model:</p>
<pre><code>class User < ActiveRecord::Base
  acts_as_emailable
  #
  # The rest of you code
end
</code></pre>
<p>Usage<br />
=====<br />
After the plugin is installed the following methods become available to your User class.</p>
<p>These methods are the associations.  They return what you would expect:</p>
<pre><code>user.users_whom_i_have_emailed
user.users_who_have_emailed_me
</code></pre>
<p>At the moment there is only bare-bones functionality, but if any interest is shown or I feel the need, I will build in some more useful methods and make it more complete&#8230;</p>
<p><strong>UPDATE</strong><br />
I am really pleased with all the interest and feedback I have received, especially from <a target="_blank" href="http://egze.blogspot.com/">egze</a> who basically did all the work for these changes.  I have now added in three new functions with two aliases as I couldn&#8217;t decide on the which I preferred:<br />
These two are really the same, they both return unread mail, although you need to make sure you update the &#8216;read_at&#8217; field in the emails table when an email is read by the receiver.</p>
<pre><code>user.unread_mail</code>
or
<code>user.new_mail</code></pre>
<p>These two return all read emails, although I&#8217;m not sure if there will be much use for it.</p>
<pre><code>user.read_mail</code>
or
<code>user.old_mail
</code>
</pre>
<p>Finally this returns all users who have emailed or been emailed by the user.</p>
<pre><code>user.all_mail</code></pre>
<p>I have a couple more ideas for new functions but suggestions are welcome.  I was also intending to write some example code but haven&#8217;t had the chance.  I&#8217;ll try to do that this week.</p>
<p><strong>UPDATE: EXAMPLE CODE</strong><br/><br />
In a REST based application the code may look something like this to send an email.  The current_user that is referred to in the create method of the emails controller can be whatever way you get the current user.  In my case I usually use Rick Olson&#8217;s <a href="http://weblog.techno-weenie.net/2006/8/1/restful-authentication-plugin">Restful Authentication</a> plugin which does this for me.<br />
app/views/emails/new.rhtml</p>
<pre>
<% form_for :email, @email, :url => emails_path(:user_id => params[:user_id]) do |f| %>
<%= render :partial => &#8216;form&#8217;, :locals => {:f => f} %>
<%= submit_tag 'Send' %>
<% end %>
</pre>
<p>app/views/emails/_form.rhtml</p>
<pre>
&lt;fieldset&gt;
    &lt;legend&gt;Email&lt;/legend&gt;
    &lt;%= f.hidden_field :receiver_id %&gt;
    &lt;div&gt;
        &lt;label for="subject"&gt;Subject&lt;/label&gt;&lt;br/&gt;
        &lt;%= f.text_field :subject %&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;label for="body">Message&lt;/label&gt;&lt;br/&gt;
        &lt;%= f.text_area :body %&gt;
    &lt;/div&gt;
&lt;/fieldset&gt;
</pre>
<p>emails_controller.rb</p>
<pre>
def index
  @emails = User.find(params[:user_id]).all_mail
end

def new
  @email = Email.new
end

def create
  current_user.send_mail(User.find(params[:user_id]), Email.new(params[:email]))
  respond_to do |format|
    format.html do
      flash[:notice] = 'Email Sent'
      redirect_to emails_path
      false;
    end
  end
rescue ActiveRecord::RecordInvalid
  render :action => 'new'
end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2007/06/05/acts_as_emailable/feed/</wfw:commentRss>
		</item>
		<item>
		<title>How to model an internal emailing system using self-referential has_many :through associations</title>
		<link>http://matt-beedle.com/2007/06/02/how-to-model-an-internal-emailing-system-using-self-referential-has_many-through-associations/</link>
		<comments>http://matt-beedle.com/2007/06/02/how-to-model-an-internal-emailing-system-using-self-referential-has_many-through-associations/#comments</comments>
		<pubDate>Sat, 02 Jun 2007 10:30:30 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2007/06/02/how-to-model-an-internal-emailing-system-using-self-referential-has_many-through-associations/</guid>
		<description><![CDATA[I am currently working on a flat sharing site.  One of the requirements is that users should be able to email each other within the site, a sort of internal emailing system.  When one user emails another user that user has an email sent to their actual email address saying that they have [...]]]></description>
			<content:encoded><![CDATA[<p>I am currently working on a flat sharing site.  One of the requirements is that users should be able to email each other within the site, a sort of internal emailing system.  When one user emails another user that user has an email sent to their actual email address saying that they have an email waiting for them on the site.  The intention being to keep them locked in to the site for as long as possible, and keep those adsense clicks coming in, and to provide a useful service of course!  In order to do this a user model needs to be able to get all users who have emailed them and also carry through associated email details.</p>
<p>Anyway, here is the migration and model code to do this:</p>
<pre><code>
class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.column 'username', :string
      t.column 'forename', :string
      t.column 'surname', :string
      t.column 'email', :string
    end
  end

  def self.down
    drop_table :users
  end
end
</code></pre>
<pre><code>
class CreateEmails < ActiveRecord::Migration
  def self.up
    create_table :emails do |t|
      t.column 'sender_id', :integer, :null => false
      t.column &#8216;receiver_id&#8217;, :integer, :null => false
      t.column &#8217;subject&#8217;, :string
      t.column &#8216;body&#8217;, :text
      t.column &#8216;created_at&#8217;, :datetime
    end
    add_index(&#8217;emails&#8217;, &#8217;sender_id&#8217;)
    add_index(&#8217;emails&#8217;, &#8216;receiver_id&#8217;)
  end

  def self.down
    drop_table :emails
  end
end
</code></pre>
<p>The important thing to notice in the User model below is that the &#8220;users_who_emailed_me&#8221; goes through &#8220;emails_as_receiver&#8221; with :source => :sender and &#8220;users_whom_i_have_emailed&#8221; goes through &#8220;emails_as_sender&#8221; with :source => :receiver.  It took me a while to figure that out.</p>
<pre><code>
class User < ActiveRecord::Base
  has_many :emails_as_sender,
    :foreign_key => &#8217;sender_id&#8217;,
    :class_name => &#8216;Email&#8217;
  has_many :emails_as_receiver,
    :foreign_key => &#8216;receiver_id&#8217;,
    :class_name => &#8216;Email&#8217;
  has_many :users_who_emailed_me,
    :through => :emails_as_receiver,
    :source => :sender
  has_many :users_whom_i_have_emailed,
    :through => :emails_as_sender,
    :source => :receiver
end
</code></pre>
<pre><code>
class Email < ActiveRecord::Base
  belongs_to :sender,
    :foreign_key => &#8217;sender_id&#8217;,
    :class_name => &#8216;User&#8217;
  belongs_to :receiver,
    :foreign_key => &#8216;receiver_id&#8217;,
    :class_name => &#8216;User&#8217;
end
</code></pre>
<p>I adapted this code from an excellent article on the excellent blog of Josh Susser which you can find <a href="http://blog.hasmanythrough.com/2006/4/21/self-referential-through">here</a>.  If fact this is pretty much the same.  However, after reading his post I did not notice the way a couple of the joins worked, which I have tried to point out here using possibly a more relevant example.</p>
<p>
<strong>UPDATE:</strong><br />
I have now packaged all of this code up into a plugin.  For install instructions read <a href="http://matt-beedle.com/2007/06/05/acts_as_emailable/">this post</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2007/06/02/how-to-model-an-internal-emailing-system-using-self-referential-has_many-through-associations/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Refactor your controller code by using postbacks</title>
		<link>http://matt-beedle.com/2007/04/03/refactor-your-controller-code-by-using-postbacks/</link>
		<comments>http://matt-beedle.com/2007/04/03/refactor-your-controller-code-by-using-postbacks/#comments</comments>
		<pubDate>Tue, 03 Apr 2007 09:20:30 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2007/04/03/refactor-your-controller-code-by-using-postbacks/</guid>
		<description><![CDATA[It is very easy to end up with an action for every single request.  You may find you generate a controller like this for example:

./script/generate controller User create_form, create, edit_form, edit

It is not necessary to have 4 actions here.  Instead this can all be handled by the same action:

def update
  @user = [...]]]></description>
			<content:encoded><![CDATA[<p>It is very easy to end up with an action for every single request.  You may find you generate a controller like this for example:</p>
<pre>
./script/generate controller User create_form, create, edit_form, edit
</pre>
<p>It is not necessary to have 4 actions here.  Instead this can all be handled by the same action:</p>
<pre>
def update
  @user = User.find_by_id(params[:id]) || User.new
  if request.post?
    @user.attributes = params[:user]
    if @user.save
      redirect_to :action => 'index'
      return
    end
  end
end
</pre>
<p>On first calling the action there is no data, and the template with your form is displayed.  Once the form is submitted to the same action, the user object is saved and the controller redirects to the home page (or the page of your choice).</p>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2007/04/03/refactor-your-controller-code-by-using-postbacks/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Using ActiveRecord to store session information in Ruby on Rails</title>
		<link>http://matt-beedle.com/2007/04/01/using-activerecord-to-store-session-information-in-ruby-on-rails/</link>
		<comments>http://matt-beedle.com/2007/04/01/using-activerecord-to-store-session-information-in-ruby-on-rails/#comments</comments>
		<pubDate>Sun, 01 Apr 2007 17:30:37 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2007/04/01/using-activerecord-to-store-session-information-in-ruby-on-rails/</guid>
		<description><![CDATA[Rails default setting is to store sessions on the file system.  This is fine during development, but this is not very scalable once an application goes into production.  Often the application will be deployed to a number of servers.  One good solution to is to use ActiveRecord to store the session information [...]]]></description>
			<content:encoded><![CDATA[<p>Rails default setting is to store sessions on the file system.  This is fine during development, but this is not very scalable once an application goes into production.  Often the application will be deployed to a number of servers.  One good solution to is to use ActiveRecord to store the session information in the database.  Fortunately this is very easy to do!</p>
<p>First of, open the config/environments.rb file and uncomment the following line:</p>
<pre><code>
config.action_controller.session_store = :active_record_store
</code></pre>
<p>Now we create the sessions table.  There is already a rake task for doing this:</p>
<pre><code>
rake db:sessions:create
rake db:migrate
</code></pre>
<p>Now restart your server and voila!  Rails does not automatically manage sessions so it is worth noting that you will need to deal with this.  If you do not you could end up with a sessions table with millions of rows.  This will slow your application down considerably.  I will post more information soon on sweepers and dealing with session expiry.</p>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2007/04/01/using-activerecord-to-store-session-information-in-ruby-on-rails/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Creating secure login code in Ruby on Rails</title>
		<link>http://matt-beedle.com/2007/03/30/creating-secure-login-code-in-ruby-on-rails/</link>
		<comments>http://matt-beedle.com/2007/03/30/creating-secure-login-code-in-ruby-on-rails/#comments</comments>
		<pubDate>Fri, 30 Mar 2007 11:30:57 +0000</pubDate>
		<dc:creator>matt</dc:creator>
		
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://matt-beedle.com/2007/03/30/creating-secure-login-code-in-ruby-on-rails/</guid>
		<description><![CDATA[Many web sites require secure user authentication, but a shocking number of them implement it very badly.  At the time of posting one of the best ways of dealing with this problem not to store the password in the database, but instead to save a &#8220;salt&#8221; and a &#8220;hash&#8221;.  The salt is a [...]]]></description>
			<content:encoded><![CDATA[<p>Many web sites require secure user authentication, but a shocking number of them implement it very badly.  At the time of posting one of the best ways of dealing with this problem not to store the password in the database, but instead to save a &#8220;salt&#8221; and a &#8220;hash&#8221;.  The salt is a set of 6 random characters which when combined with the users password and encoded, is equal to the hash.  Before going any further, you should be aware that there are plugins for rails which deal with salted logins (<a href="http://wiki.rubyonrails.org/rails/pages/SaltedHashLoginGenerator">http://wiki.rubyonrails.org/rails/pages/SaltedHashLoginGenerator</a>), but I believe it is best to be able to write the code yourself, or at least to have a basic understanding.</p>
<p>user migration</p>
<pre>
  t.column :username, :string
  t.column :password_salt, :string
  t.column :password_hash, :string
</pre>
<p>app/models/user.rb:</p>
<pre>
require 'digest/sha2'
class User < ActiveRecord::Base
  attr_accessor :password

  def password=(pass)
    salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
    self.password_salt, self.password_hash = salt, Digest::SHA256.hexdigest(pass + salt)
  end

  def self.authenticate(username, password)
    user = User.find(:first, :conditions => [&#8221;username = ?&#8221;, username])
    if user.blank? || Digest::SHA256.hexdigest(password + user.password_salt) != user.password_hash
      raise &#8220;Username or password invalid&#8221;
    end
    user
  end
end
</pre>
<p>application_controller.rb</p>
<pre>
  def check_authentication
    if session[:user].blank?
      session[:intended_controller] = controller_name
      session[:intended_action] = action_name
      redirect_to :controller => 'user', :action => 'login'
    end
  end
</pre>
<p>app/controllers/user_controller.rb:</p>
<pre>
def login
    if request.post?
      begin
        session[:user] = User.authenticate(params[:username],params[:password]).id
        redirect_to :controller => session[:intended_controller], :action => session[:intended_action]
      rescue
        flash[:notice] = "Username or password invalid"
      end
    end
  end

  def logout
    session[:user] = nil
    redirect_to :controller => :user, :action => :index
  end

def register
    if request.post?
        @user = User.new(params[:user])
        if @user.save
          redirect_to :action => :account_creation_success, :id => @user
        end
      end
    end
</pre>
<p>app/views/user/login.rhtml:</p>
<pre>

<%= flash[:notice] -%>

<% form_tag :controller => :user, :action => :login do %>
&lt;fieldset&gt;
<div>
                &lt;label for=&#8221;user_username&#8221;&gt;Username&lt;/label&gt;
                <%= text_field 'user', 'username' -%>
        </div>
<div>
                &lt;label for=&#8221;user_password&#8221;&gt;Password&lt;/label&gt;
                <%= password_field 'user', 'password' -%>
        </div>

&lt;/fieldset&gt;
<%= submit_tag 'Login' -%>
<% end %>
</pre>
<p>app/views/user/register.rhtml:</p>
<pre>
<% form_tag :controller => :user, :action => :register do %>
&lt;fieldset&gt;
<div>
        &lt;label for=&#8221;username&#8221;&gt;Username&gt;/label&gt;
        <%= text_field_tag 'user', nil, 'username' -%>
    </div>
<div>
        &lt;label for=&#8221;password&#8221;&gt;Password&lt;/label&gt;
        <%= password_field_tag 'user', nil, 'password' -%>
    </div>

&lt;/fieldset&gt;
<%= submit_tag 'Register' -%>
<% end %>
</pre>
<p>Now use a before_filter on any controllers where you need to login.</p>
]]></content:encoded>
			<wfw:commentRss>http://matt-beedle.com/2007/03/30/creating-secure-login-code-in-ruby-on-rails/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
