<?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>this oughta be interesting...</title>
	<atom:link href="http://joshsharpe.com/feed" rel="self" type="application/rss+xml" />
	<link>http://joshsharpe.com</link>
	<description></description>
	<lastBuildDate>Tue, 06 Dec 2011 17:52:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>skinny models! yay!</title>
		<link>http://joshsharpe.com/archives/skinny-models-yay</link>
		<comments>http://joshsharpe.com/archives/skinny-models-yay#comments</comments>
		<pubDate>Tue, 06 Dec 2011 17:46:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=178</guid>
		<description><![CDATA[This guy doesn&#8217;t deserve credit for this idea, but his explanation is on point. http://qualityonrails.com/archives/33]]></description>
			<content:encoded><![CDATA[<p>This guy doesn&#8217;t deserve credit for this idea, but his explanation is on point.</p>
<p><a href="http://qualityonrails.com/archives/33">http://qualityonrails.com/archives/33</a></p>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/skinny-models-yay/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails3 Upgrade #1 &#8211; Delayed Mailers</title>
		<link>http://joshsharpe.com/archives/rails3-upgrade-1-delayed-mailers</link>
		<comments>http://joshsharpe.com/archives/rails3-upgrade-1-delayed-mailers#comments</comments>
		<pubDate>Wed, 26 Jan 2011 16:22:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[action mailer]]></category>
		<category><![CDATA[delayed job]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=158</guid>
		<description><![CDATA[Sending emails inside your request/response cycle is one of the slower things you can do to users. A while ago, I contrived a way to delay every single email in my application in one fell swoop, without having to change my models and controllers that were actually sending the email. That is, I wanted to [...]]]></description>
			<content:encoded><![CDATA[<p>Sending emails inside your request/response cycle is one of the slower things you can do to users.  A while ago, I contrived a way to delay  every single email in my application in one fell swoop, without having to change my models and controllers that were actually sending the email.  That is, I wanted to keep the existing deliver_* calls in tact, so that my application code continued to look like rails code.</p>
<p>In Rails 2.3.x, using Delayed Job, here is what I did:</p>
<p>For the record, I only have a single ActionMailer subclass, so this simplifies things quite a bit.  In the event you have more than one you&#8217;ll need to modify the following to also pass the class name to delayed job. (not hard)</p>
<pre>
class Notifier < ActionMailer::Base

  #...a bunch of mailer methods

  def self.method_missing(method, *args)
   if method.to_s.match(/^deliver_(.*)/)
     Delayed::Job.enqueue(DelayedNotifier.new("create_#{$1}", args))
    else
      super(method, *args)
    end
  end
</pre>
<p>In a nutshell, we're hijacking ActionMailer's built-in deliver_* methods, changing them to create_* methods, and sending it to delayed job.  Here's what Delayed Notifier is:</p>
<pre>
 class DelayedNotifier < Struct.new(:method, :args)
   def perform
    mail = Notifier.send(method, *args)
    Notifier.deliver(mail)
   end
 end
</pre>
<p>The class that you send to delayed job must respond to #perform in order for Delayed Job to work correctly.  So, delayed job grabs the method name, the arguments that were passed in, builds the TMail object and sends it.  Again, since I only have a single Mailer class, I don't need to worry about passing around the name of that class.</p>
<p>Note that the call from your controller/model to deliver_* doesn't actually build a Tmail object.*** All it does is build the DelayedNotifier object and save it to the DB.  So our servers are *not* creating emails and sending them once.   That would be lame.</p>
<p>Well, this broke with Rails 3. </sadface></p>
<p>Rails 3's ActionMailer API is a bit different than the deliver_* methods that we've been used to.  It looks like this:</p>
<p>Notifier.password_reset_instructions(user).deliver</p>
<p>Well, crap, now it looks like I *have* to build the <del datetime="2011-01-26T15:54:12+00:00">TMail</del> Mail object inside of the request/response cycle.  I really don't want to do that, sooooo, let's bring deliver_* back.  Yea, seriously.</p>
<pre>
class Notifier < ActionMailer::Base
  def self.method_missing(method, *args)
    if method.to_s.match(/^deliver_(.*)/)
      Delayed::Job.enqueue(DelayedNotifier.new($1, args))
    else
      super(method, *args)
    end
  end
end
</pre>
<p>And the new, fancy Delayed Notifier struct:</p>
<pre>
 class DelayedNotifier < Struct.new(:method, :args)
   def perform
     Notifier.send(method, *args).deliver
   end
 end
</pre>
<p>You use this the same way you used mailers in rails 2.3.x.  That is, with deliver_*.  Blasphemy, I know, but look on the bright side:  Now you don't have to grep your code and update all calls to deliver_*.  Sweet!</p>
<p>P.S.</p>
<p>Delayed Job allows you to handle exceptions as you see fit, and hoptoad handles exception notification like no other.  It's a match made in heaven.</p>
<pre>
require 'hoptoad_notifier'

class DelayedNotifier < Struct.new(:method, :args)
  def perform
    Notifier.send(method, *args).deliver
  end

  def failure(job, exception)
    HoptoadNotifier.notify(exception)
  end
end
</pre>
<p>***<br />
TMail objects are very large  (html, plain text, headers, attachments, etc...).  If you designed this such that the controller built the TMail object, and then saved that to the DB, you would need to make your delayed_jobs' handler column's type mediumtext or bigger, since you run the risk of there not being enough room in the column for the entire TMail object.  Also, you're building the TMail object inside the request/response cycle which is slow and completely unnecessary.  Keep it simple, save the method name and the arguments required to build the TMail object and let Delayed Job do the rest.</p>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/rails3-upgrade-1-delayed-mailers/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rails3 Upgrade Intro</title>
		<link>http://joshsharpe.com/archives/rails3-upgrade-intro</link>
		<comments>http://joshsharpe.com/archives/rails3-upgrade-intro#comments</comments>
		<pubDate>Wed, 26 Jan 2011 15:54:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=151</guid>
		<description><![CDATA[I launched into a rails 3 upgrade for my main side project last night. I&#8217;m going to use it as an excuse to blog about a bunch of things that I&#8217;ve been meaning to write about, but never got around to. Here&#8217;s a quick look at the scope of this app: $ rake stats +----------------------+-------+-------+---------+---------+-----+-------+ [...]]]></description>
			<content:encoded><![CDATA[<p>I launched into a rails 3 upgrade for my main side project last night.  I&#8217;m going to use it as an excuse to blog about a bunch of things that I&#8217;ve been meaning to write about, but never got around to.</p>
<p>Here&#8217;s a quick look at the scope of this app:</p>
<pre>
$ rake stats
+----------------------+-------+-------+---------+---------+-----+-------+
| Name                 | Lines |   LOC | Classes | Methods | M/C | LOC/M |
+----------------------+-------+-------+---------+---------+-----+-------+
| Controllers          |  1867 |  1616 |      23 |     154 |   6 |     8 |
| Helpers              |   403 |   351 |       0 |      55 |   0 |     4 |
| Models               |  3310 |  2701 |      58 |     331 |   5 |     6 |
| Libraries            |   441 |   401 |       2 |      38 |  19 |     8 |
| Integration tests    |   600 |   340 |       4 |       6 |   1 |    54 |
| Functional tests     |  8763 |  8421 |      22 |      21 |   0 |   399 |
| Unit tests           |  5230 |  4794 |      85 |      10 |   0 |   477 |
+----------------------+-------+-------+---------+---------+-----+-------+
| Total                | 20614 | 18624 |     194 |     615 |   3 |    28 |
+----------------------+-------+-------+---------+---------+-----+-------+
  Code LOC: 5069     Test LOC: 13555     Code to Test Ratio: 1:2.7
</pre>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/rails3-upgrade-intro/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I don&#8217;t know, can you?</title>
		<link>http://joshsharpe.com/archives/i-dont-know-can-you</link>
		<comments>http://joshsharpe.com/archives/i-dont-know-can-you#comments</comments>
		<pubDate>Mon, 01 Mar 2010 19:05:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=100</guid>
		<description><![CDATA[&#60;rant&#62; There has been, and continues to be, a lot of talk around writing semantic code. One thing that gets under my skin, and I wish it would stop, is the continued use of #can?(:do_something) as a pattern for handling permissions. I have no problem with the pattern itself, it&#8217;s the verb I take issue [...]]]></description>
			<content:encoded><![CDATA[<p>&lt;rant&gt;</p>
<p>There has been, and continues to be, a lot of talk around writing semantic code.  One thing that gets under my skin, and I wish it would stop, is the continued use of #can?(:do_something) as a pattern for handling permissions.  I have no problem with the pattern itself, it&#8217;s the verb I take issue with.  &#8220;Can&#8221; asks for the ability to do something, &#8220;may&#8221; asks for permission&#8221;  Get it right people.</p>
<p>Doesn&#8217;t anyone else remember the following scenario from second grade?</p>
<p>Miniature you:  &#8220;Teacher, teacher! Can I go do the bathroom, please?&#8221;<br />
Mrs. WhatsHerName:  &#8220;I don&#8217;t know, can you?&#8221;<br />
Miniature, pissed off, you:  &#8220;Well, yea, I can&#8230;&#8221; &lt;blank stare /&gt;</p>
<p>I&#8217;m looking at you <a href="http://github.com/ryanb/cancan">cancan</a>, <a href="http://github.com/jnunemaker/canable/">canable</a> and <a href="http://github.com/noomii/walruz-rails">walruz</a>.</p>
<p>If you still don&#8217;t get it <a href="http://www.businesswritingblog.com/business_writing/2006/08/can_vs_maynot_s.html">read this</a>.</p>
<p>As far as I know, the only plugin out there that handles this (semantic issue) correctly is <a href="http://github.com/makandra/aegis">Makandra&#8217;s Aegis</a>.  And they are <a href="http://github.com/makandra">GERMAN</a>. It functionally works about the same as well.  So props to them for that.</p>
<p>&lt;/rant&gt;</p>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/i-dont-know-can-you/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>jquery.dateTimePicker</title>
		<link>http://joshsharpe.com/archives/jquery-datetimepicker-2</link>
		<comments>http://joshsharpe.com/archives/jquery-datetimepicker-2#comments</comments>
		<pubDate>Wed, 10 Feb 2010 21:44:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=94</guid>
		<description><![CDATA[I did a ground up re-write of my date-time picker. It now only relies on jQuery (1.4.1) and jQuery UI (1.8rc1). Use case is pretty simple right now: $(function(){ $('#datetimepicker').dateTimePicker(); $('#datepicker').dateTimePicker({showTime: false}); $('#timepicker').dateTimePicker({showDate: false}); }); See the demo for more details. Enjoy!]]></description>
			<content:encoded><![CDATA[<p>I did a ground up re-write of my <a href="http://crankharder.github.com/jquery.dateTimePicker/">date-time picker</a>.  It now only relies on jQuery (1.4.1) and jQuery UI (1.8rc1).</p>
<p>Use case is pretty simple right now:</p>
<pre>
$(function(){
  $('#datetimepicker').dateTimePicker();
  $('#datepicker').dateTimePicker({showTime: false});
  $('#timepicker').dateTimePicker({showDate: false});
});
</pre>
<p>See the demo for more details. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/jquery-datetimepicker-2/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>error and success messages and the like&#8230;</title>
		<link>http://joshsharpe.com/archives/error-and-success-messages-and-the-like</link>
		<comments>http://joshsharpe.com/archives/error-and-success-messages-and-the-like#comments</comments>
		<pubDate>Mon, 25 Jan 2010 21:58:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=42</guid>
		<description><![CDATA[For one of my apps I&#8217;ve developed what I think is a very easy to use and consistent way of handling error and success messages throughout my app. It would be a lie if I called the following list a set of goals since they evolved over time, but there&#8217;s definitely a bit of philosophy [...]]]></description>
			<content:encoded><![CDATA[<p>For one of my apps I&#8217;ve developed what I think is a very easy to use and consistent way of handling error and success messages throughout my app.  It would be a lie if I called the following list a set of goals since they evolved over time, but there&#8217;s definitely a bit of philosophy driving any future changes that I make to this aspect of the system.</p>
<p>1) Error/Success messages should look and feel the same throughout the application.  This means that the HTML and CSS that displays them should be located in one place and not scattered across several different views and stylesheets.  It also shouldn&#8217;t matter if there is one error or a list of errors.</p>
<p>2) I should be able to generate and display these errors whether this is a synchronous or an asynchronous request.</p>
<p>3) Everything should quack.</p>
<h3>The Setup</h3>
<p>The relevant code from ApplicationController:</p>
<pre>
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base

  helper_method :errors_for, :success_for

private

  def success_for(message)
    unless message.blank?
      render_to_string :partial => 'shared/success', :locals => {:message => message}
    end
  end

  def errors_for(object)
    unless object.respond_to?(:errors) &#038;&#038; object.errors.empty?
      render_to_string :partial => 'shared/error', :locals => {:object => object}
    end
  end
end
</pre>
<p>Making them helper methods is a necessary evil so that they can be called from both the controller and the view.  Calling them from the view should be obvious.  Say you have an Active Record object with errors on it:</p>
<pre>
= errors_for @user_with_errors
</pre>
<p>&#8230;and calling it from inside a controller is extremely useful when you need to pass errors back to an AJAX request:</p>
<pre>
render :json => {:errors => errors_for(user_with_errors)}
</pre>
<p>This is where people start to get feisty.  &#8220;You shouldn&#8217;t be passing HTML back with JSON.  JSON is for passing raw data.&#8221;  I say rules are meant to be broken.  If I passed the raw data (the errors) back in JSON I would have to create the associated markup in javascript.  So not only am I duplicating logic, I&#8217;m doing it in two different languages (javascript, ERB/HAML).  That sucks.</p>
<p>Here&#8217;s my error partial, in HAML:</p>
<pre>
-if object.is_a?(String) || object.is_a?(Array)
  .errorWrapper{:style => "width:#{display_width(object)}px;"}
    -if object.is_a? String
      %p= object
    -elsif object.is_a? Array
      %ul
        -object.each do |message|
          %li= message
-elsif object.kind_of?(ActiveRecord::Base) || object.kind_of?(Authlogic::Session::Base)
  .errorWrapper{:style => "width:#{display_width(object)}px;"}
    =error_messages_for(:object => object, :id => nil, :header_message => nil, :message => nil)
</pre>
<p>I know that kind of looks a mess, and some slight duplication, but it&#8217;s all for the greater good.  First off, the partial renders nothing if it gets passed the wrong Thing.  Secondly, it&#8217;s wrapped up nicely by errorWrapper, which gives us a consistent place to start writing styles from.  We do this since you cannot (currently) change the class that error_messages_for gives you.  Thirdly, we&#8217;re using error_message_for so that we can seamlessly pass ActiveRecord and AuthLogic objects and it won&#8217;t blink.</p>
<p>The success partial is a bit simpler since we don&#8217;t expect objects to have &#8220;success&#8221; messages attached to them.  Instead it accepts single strings or an array of strings:</p>
<pre>
.success{:style => "width:#{display_width(object)}px;"}
  -if object.is_a? String
    %p= object
  -elsif object.is_a? Array
    %ul
      -object.each do |message|
        %li= message
</pre>
<p>And finally, a bit of &#8220;making things look nicer&#8221;:</p>
<pre>
module ApplicationHelper
  ERROR_COEF = 8.0
  def display_width(object)
    (if object.is_a?(String)
      object.length
    elsif object.is_a?(ActiveRecord::Base) || object.is_a?(UserSession)
      object.errors.full_messages.map(&#038;:length).max
    elsif object.is_a?(Array)
      object.map(&#038;:length).max
    end * ERROR_COEF).to_i
  end
end
</pre>
<p>A bit of a mess again, but what we&#8217;re doing here is defining a width for the wrapping container based on the length of the error messages.  This is so that we don&#8217;t just arbitrarily set our container to be 600px wide for errors that are only three words.  (This looks pretty awful)  You might need to play around with that coefficient a bit to make it work with the rest of your styles &#8212; and even that may not be very precise.  That said, I&#8217;ve yet to run into any error or set of errors that this didn&#8217;t handle very nicely.</p>
<h3>The Rub</h3>
<p>So how do we use all of this?  Pretty much any way you want!  Throw an errors_for(@object) in your edit template and forget it.  If @object has errors on it, they get displayed, if not, then no markup is generated.  Not even a wrapping container.</p>
<p>Want to create an array of errors for an AJAX request and display them?  No problem.</p>
<pre>
error_messages = []
error_messages << "Err"
error_messages << "Foo"
render :json => {:errors => errors_for(error_messages)}
</pre>
<p>Then, in your javascript (jQuery)</p>
<pre>
$('form#login').prepend(response.errors);
</pre>
<p>What about success messages?  They&#8217;re probably passed in some kind of Flash.</p>
<pre>
Controller:
flash[:success] = "The post was successful"

View
=success_for flash[:success]
</pre>
<p>This is what I&#8217;m doing, how are you handling this problem?</p>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/error-and-success-messages-and-the-like/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SSL! Abort Trap! Egad!</title>
		<link>http://joshsharpe.com/archives/ssl-abort-trap-egad</link>
		<comments>http://joshsharpe.com/archives/ssl-abort-trap-egad#comments</comments>
		<pubDate>Wed, 06 Jan 2010 15:23:12 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[rvm]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=76</guid>
		<description><![CDATA[This recently happened to me: $ rake db:migrate /Users/jsharpe/.rvm/ree-1.8.7-2009.10/lib/ruby/1.8/openssl/ssl.rb:31: [BUG] Bus Error ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin9.8.0], MBARI 0x8770, Ruby Enterprise Edition 2009.10 Abort trap I&#8217;m really not sure who the culprit is here. I don&#8217;t think it&#8217;s REE since it also happens with 1.8.7. So is it 1.8.7? Is it RVM? Openssl? Or [...]]]></description>
			<content:encoded><![CDATA[<p>This recently happened to me:</p>
<pre>
$ rake db:migrate
/Users/jsharpe/.rvm/ree-1.8.7-2009.10/lib/ruby/1.8/openssl/ssl.rb:31: [BUG] Bus Error
ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin9.8.0], MBARI 0x8770, Ruby Enterprise Edition 2009.10

Abort trap
</pre>
<p>I&#8217;m really not sure who the culprit is here.  I don&#8217;t think it&#8217;s REE since it also happens with 1.8.7.  So is it 1.8.7?  Is it RVM?  Openssl?  Or is it me? Whatever the case this took me a LONG time to figure out &#8211; I hope this post saves many thousands of people countless wasted hours.</p>
<p>Add this to ~/.bash_profile</p>
<pre>
export RUBYOPT="-ropenssl"
</pre>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/ssl-abort-trap-egad/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>nested relations in ActiveRecord</title>
		<link>http://joshsharpe.com/archives/nested-relations-in-activerecord</link>
		<comments>http://joshsharpe.com/archives/nested-relations-in-activerecord#comments</comments>
		<pubDate>Fri, 13 Nov 2009 22:09:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[active record]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=56</guid>
		<description><![CDATA[I personally don&#8217;t think this is all that exciting &#8212; but I see this question asked a lot and just want something to point at from now on. Say you have several &#8216;nested&#8217; has_many relations: class State < ActiveRecord::Base has_many :cities end class City < ActiveRecord::Base has_many :streets belongs_to :state end class Street < ActiveRecord::Base [...]]]></description>
			<content:encoded><![CDATA[<p>I personally don&#8217;t think this is all that exciting &#8212; but I see this question asked a lot and just want something to point at from now on.</p>
<p>Say you have several &#8216;nested&#8217; has_many relations:</p>
<pre>
class State < ActiveRecord::Base
  has_many :cities
end

class City < ActiveRecord::Base
  has_many :streets
  belongs_to :state
end

class Street < ActiveRecord::Base
  has_many :houses
  belongs_to :city
end

class House < ActiveRecord::Base
  belongs_to :street
end
</pre>
<p>How do you get all of the Houses in virginia?</p>
<p>Well, you could do this:</p>
<pre>
virginia.cities.collect{|c| c.streets}.flatten.uniq.collect{|s| s.houses}.flatten.uniq
</pre>
<p>... but that's epically lame.  It looks like shit and produces an metric ton of queries and as a result is highly inefficient.</p>
<p>How about this:</p>
<pre>
House.find(
  :all,
  :include => {:street => {:city => :state}},
  :conditions => {'states.id' => virginia.id}
)
</pre>
<p>This is a single query with joins where appropriate, and it's a finder on House which is what you're getting anyways.  Makes sense, no?</p>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/nested-relations-in-activerecord/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>the single best active record learning tool that exists. period. the end.</title>
		<link>http://joshsharpe.com/archives/the-single-best-active-record-learning-tool-that-exists-period-the-end</link>
		<comments>http://joshsharpe.com/archives/the-single-best-active-record-learning-tool-that-exists-period-the-end#comments</comments>
		<pubDate>Tue, 27 Oct 2009 22:17:27 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[active record]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=3</guid>
		<description><![CDATA[Every once in a while I see this little code snippet show up somewhere: script_console_running = ENV.include?('RAILS_ENV') &#38;&#38; IRB.conf[:LOAD_MODULES] &#38;&#38; IRB.conf[:LOAD_MODULES].include?('console_with_helpers') rails_running = ENV.include?('RAILS_ENV') &#38;&#38; !(IRB.conf[:LOAD_MODULES] &#38;&#38; IRB.conf[:LOAD_MODULES].include?('console_with_helpers')) irb_standalone_running = !script_console_running &#38;&#38; !rails_running if script_console_running require 'logger' Object.const_set(:RAILS_DEFAULT_LOGGER, Logger.new(STDOUT)) end You see, if you drop this little gem in ~/.irbrc you&#8217;ll start getting the SQL [...]]]></description>
			<content:encoded><![CDATA[<p>Every once in a while I see this little code snippet show up somewhere:</p>
<pre>
script_console_running = ENV.include?('RAILS_ENV') &amp;&amp;
                         IRB.conf[:LOAD_MODULES] &amp;&amp;
                         IRB.conf[:LOAD_MODULES].include?('console_with_helpers')
rails_running = ENV.include?('RAILS_ENV') &amp;&amp;
                !(IRB.conf[:LOAD_MODULES] &amp;&amp;
                IRB.conf[:LOAD_MODULES].include?('console_with_helpers'))
irb_standalone_running = !script_console_running &amp;&amp; !rails_running
if script_console_running
  require 'logger'
  Object.const_set(:RAILS_DEFAULT_LOGGER, Logger.new(STDOUT))
end
</pre>
<p>You see, if you drop this little gem in ~/.irbrc you&#8217;ll start getting the SQL output from your various ruby commands.  This is an excellent <em>debugging</em> tool, but it&#8217;s an even better <em>learning</em> tool.</p>
<p>To the novice the difference between the following two statements may not be readily apparent&#8230;</p>
<pre>
User.find(:first).posts.each{|p| p.comments.do_something}
User.find(:first, :include => {:posts => :comments}).posts.each{|p| p.comments.do_something}
</pre>
<p>&#8230;but as soon as they sit and watch what scrolls by in the terminal they will *very* quickly realize that one of them is *very* wrong.</p>
<p>I submit that the next time you are teaching anyone the basics of AR that this be the very first thing that you introduce them to.</p>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/the-single-best-active-record-learning-tool-that-exists-period-the-end/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>redirect back or default &#8212; you&#8217;re (probably) doing it wrong</title>
		<link>http://joshsharpe.com/archives/redirect-back-or-default-youre-probably-doing-it-wrong</link>
		<comments>http://joshsharpe.com/archives/redirect-back-or-default-youre-probably-doing-it-wrong#comments</comments>
		<pubDate>Fri, 23 Oct 2009 01:17:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[authentication]]></category>

		<guid isPermaLink="false">http://joshsharpe.com/?p=5</guid>
		<description><![CDATA[A basic authentication scheme should go to some length to do a little bit of remembering in the event your user hits a restricted page before they are actually authenticated. First, some context. I&#8217;ve got this in my ApplicationController: def require_user unless current_user store_location redirect_to login_path return false end end def store_location session[:return_to] = request.request_uri [...]]]></description>
			<content:encoded><![CDATA[<p>A basic authentication scheme should go to some length to do a little bit of remembering in the event your user hits a restricted page before they are actually authenticated.</p>
<p>First, some context.  I&#8217;ve got this in my ApplicationController:</p>
<pre>
def require_user
  unless current_user
    store_location
    redirect_to login_path
    return false
  end
end

def store_location
  session[:return_to] = request.request_uri
end

def redirect_back_or_default(default)
  redirect_to(session[:return_to] || default)
  session[:return_to] = nil
end
</pre>
<p>&#8230; which allows me to do this in any of my controllers:</p>
<pre>before_filter :require_user, :except =&gt; [:index, :show]</pre>
<p>&#8230; and this is cool because now my users get redirected back to where they were going after they log in.  I like saving my users a click or two here and there if at all possible.</p>
<p>There&#8217;s a problem with this though.  What happens if somehow your user POSTs to an action that is behind <code>require user</code>?  Well <code>request.request_uri</code> is *not* what you want to redirect to.  Why? Because redirect_to is going GET the same url that your user was trying to POST to.  And if you&#8217;re being a good Rails developer and using resources then you&#8217;re just going to smack them in a face with a big fat 404, and that&#8217;s not very nice.</p>
<p>I actually managed to do all of this over at <a href="http://www.github.com">github</a> earlier today by trying to comment on a commit without being logged in.  Want to see it in action? (until github fixes their ways)  First, go to <a href="http://www.github.com">github</a> and logout.  Then find any commit and try to make a comment, you can figure the rest out.  Go ahead, I&#8217;ll wait.</p>
<p>What is that critter anyways? It&#8217;s like a half octopus with a lizard tail and whiskers.  wtf.</p>
<p>Anyways, here&#8217;s the simple fix:</p>
<pre>
def store_location
  session[:return_to] =
  if request.get?
    request.request_uri
  else
    request.referer
  end
end
</pre>
<p>If they&#8217;re GETing something let em keep on GETing it, otherwise take them back to where they were coming from.</p>
<p>This solution is only half-baked though.  Any form data that the user has filled out will be gone and they&#8217;ll have to redo it.   On the other hand you really shouldn&#8217;t be showing a form to an unauthenticated user that requires them to be logged in to hit it.  If you really insist on doing that have fun saving all those parameters in the session or somethin in between requests.  I&#8217;d imagine that&#8217;ll suck.</p>
]]></content:encoded>
			<wfw:commentRss>http://joshsharpe.com/archives/redirect-back-or-default-youre-probably-doing-it-wrong/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
