<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Codeshooter's Weblog</title>
	<atom:link href="http://codeshooter.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://codeshooter.wordpress.com</link>
	<description>A programmer's shooting range</description>
	<lastBuildDate>Mon, 09 Nov 2009 02:53:59 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='codeshooter.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/96443d656a354153e2bf562cdb17a3e5?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Codeshooter's Weblog</title>
		<link>http://codeshooter.wordpress.com</link>
	</image>
			<item>
		<title>If you’re cleaning up your user’s input in your views you’re doing it wrong</title>
		<link>http://codeshooter.wordpress.com/2009/11/08/if-you%e2%80%99re-cleaning-up-your-user%e2%80%99s-input-in-your-views-you%e2%80%99re-doing-it-wrong/</link>
		<comments>http://codeshooter.wordpress.com/2009/11/08/if-you%e2%80%99re-cleaning-up-your-user%e2%80%99s-input-in-your-views-you%e2%80%99re-doing-it-wrong/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 02:53:59 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[actionpack]]></category>
		<category><![CDATA[data sanitization]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=98</guid>
		<description><![CDATA[Have you ever found yourself using the &#8220;h&#8221; view helper all around your views in your applications? Have you ever thought that cleaning up user input in views is a tedious, error prone and cumbersome job?
You&#8217;re not alone.
Think with me, the user provides information once to your application, that information could be badly formatted, could [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=98&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Have you ever found yourself using the &#8220;h&#8221; view helper all around your views in your applications? Have you ever thought that cleaning up user input in views is a tedious, error prone and cumbersome job?</p>
<p>You&#8217;re not alone.</p>
<p>Think with me, the user provides information <strong>once</strong> to your application, that information could be badly formatted, could be an XSS attack, but you store it as the user provided in your database. When you&#8217;re about to show that information, something that could happen once or a hundred of times (you probably would like to have thousands of page views, wouldn’t you?) you finally clean it up, instead of cleaning it up just once when the user provided it.</p>
<p>Insane, heh?</p>
<p>What about stopping with this waste of CPU cycles and cleaning the data once and for all?</p>
<p>Don&#8217;t worry, you don&#8217;t have to do anything, it&#8217;s already done and sorted out for you with this dead simple plugin. The params_sanitizer plugin uses Rails own sanitizers to clean the user input when it&#8217;s first provided on form POSTs and PUTs (what? do you change your application/database state with GET calls? OMFG!). You can protect all calls to all controllers, protect all actions in a single controller and even protect specific actions in a single controller, it&#8217;s your call!</p>
<p>First step is to install the <a href="http://github.com/mauricio/params_sanitizer">plugin</a>:</p>
<p>ruby script/plugin install git://github.com/mauricio/params_sanitizer.git</p>
<p>With the plugin installed, you can start cleaning up user input in your application once and forgetting about it forever, here are the examples:<br />
Stripping tags from all params in all actions (remember, only POST or PUT actions will really be changed ):</p>
<pre class="brush: ruby;">class ApplicationController &lt; ActionController::Base
  strip_tags_from_params #strip_tags users rails full_sanitizer
end</pre>
<p>Stripping tags from all params for all actions in a single controller:</p>
<pre class="brush: ruby;">class NewsStoriesController &lt; ApplicationController
  strip_tags_from_params
end</pre>
<p>Stripping tags from all params for specific actions in a single controller:</p>
<pre class="brush: ruby;">class CommentsController &lt; ApplicationController
  strip_tags_from_params :only =&gt; [ :create, :update ]
end</pre>
<p>If instead of stripping all tags, you&#8217;d just like to use the simple sanitizer  (it removes bad tags like  but would leave others intact, uses rails white_list_sanitizer):</p>
<pre class="brush: ruby;">class ApplicationController &lt; ActionController::Base
  sanitize_params
end

class NewsStoriesController &lt; ApplicationController
  sanitize_params
end

class CommentsController &lt; ApplicationController
  sanitize_params :only =&gt; [ :create, :update ]
end</pre>
<p>This plugin depends only on Rails default sanitizers, so you don&#8217;t need to install anything else to have it working.</p>
<p>Now, as the data is cleanly stored in your database, you don’t have to waste CPU cycles cleaning up data in your view layer (and you can even say that you’re more adherent to the MVC, as cleaning up user input was never one of it’s jobs).</p>
Posted in ruby, ruby on rails Tagged: actionpack, data sanitization, MVC, rails, ruby <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/98/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=98&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/11/08/if-you%e2%80%99re-cleaning-up-your-user%e2%80%99s-input-in-your-views-you%e2%80%99re-doing-it-wrong/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
		<item>
		<title>Building your own ActiveRecord validation macros with validates_each</title>
		<link>http://codeshooter.wordpress.com/2009/09/28/building-your-own-activerecord-validation-macros-with-validates_each/</link>
		<comments>http://codeshooter.wordpress.com/2009/09/28/building-your-own-activerecord-validation-macros-with-validates_each/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 12:31:05 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[activerecord]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[validations]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=93</guid>
		<description><![CDATA[A common task when writing your own Rails applications using ActiveRecord is creating your own validations for your models. While it’s perfectly correct to add the validation directly into the model you’re going to need it, sometimes you’d like to reuse the same validation logic  in other models and we’re not really going to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=93&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A common task when writing your own Rails applications using ActiveRecord is creating your own validations for your models. While it’s perfectly correct to add the validation directly into the model you’re going to need it, sometimes you’d like to reuse the same validation logic  in other models and we’re not really going to do a cut-and-paste here are we?</p>
<p>The simplest solution when you’re validating fields (and not the whole model) is to use the validates_each method, as it has some nice features seen in other validations that might interest you as the :if, :unless, :allow_blank and :allow_nil options.</p>
<p>Our custom example validation is to validate that one or more fields are different from one specific field. Imagine that you’re building an invoices application, having the seller to also be the buyer isn’t really what you’re looking for, so that’s why we’re building this validation. Let’s take a look at the validation code:</p>
<pre class="brush: ruby;">ActiveRecord::Base.class_eval do

  def self.validates_different( *args )

    options = args.extract_options!
    raise &quot;You must define a :field option to compare to&quot; if options[:field].blank?

    validates_each(*(args &lt;&lt; options)) do |record, attribute, value|
      if record.send( options[:field] ) == value
        record.errors.add(
          attribute,
          record.errors.generate_message(
            attribute
            'different',
            :field =&gt; record.class.human_attribute_name( options[:field].to_s ) ) )
      end
      true
    end

  end

end</pre>
<p>We have inserted a static method inside the ActiveRecord::Base class to be our validation macro, it takes a list of parameters and an options hash at the end, here’s a sample of how it would be used:</p>
<pre class="brush: ruby;">class Invoice &lt; ActiveRecord::Base
    validates_different :seller_id, :field =&gt; :buyer_id, :allow_blank =&gt; true
end</pre>
<p>The validation looks just like any other ActiveRecord validation and even uses options well known in them like :allow_blank, keeping the principle of least surprise at bay. It’s also important to notice the use of I18N on the validation message, the “&#8217;activerecord.errors.messages” namespace is the ActiveRecord error messages namespace and that’s where you should add your custom validation messages, do not place the messages directly inside your validation or model code. Here’s how the YAML file would look like:</p>
<pre class="brush: plain;">en:
  activerecord:
    errors:
      messages:
        different: “must be different than {{field}}”</pre>
<p>And there you go, you have built your own validation macro for your ActiveRecord models and even used the I18N helpers to keep the messages away from your model code.</p>
Posted in ruby, ruby on rails Tagged: activerecord, rails, ruby, validations <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/93/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/93/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/93/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=93&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/09/28/building-your-own-activerecord-validation-macros-with-validates_each/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
		<item>
		<title>Setting a far future expires header for your Rails app static assets in your Nginx server</title>
		<link>http://codeshooter.wordpress.com/2009/09/21/setting-a-far-future-expires-header-for-your-rails-app-static-assets-in-your-nginx-server/</link>
		<comments>http://codeshooter.wordpress.com/2009/09/21/setting-a-far-future-expires-header-for-your-rails-app-static-assets-in-your-nginx-server/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 01:50:25 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[front end performance]]></category>
		<category><![CDATA[nginx]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=89</guid>
		<description><![CDATA[Setting a far future expires header for your static assets is one of the first front end performance improvements you must do in your web applications. This will tell your user’s browser to keep the static assets cached and they won’t make unnecessary HTTP requests just to see that the version they currently have is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=89&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Setting a far future expires header for your static assets is one of the first front end performance improvements you must do in your web applications. This will tell your user’s browser to keep the static assets cached and they won’t make unnecessary HTTP requests just to see that the version they currently have is already the latest and this will surely improve your website’s perceived performance (yes, there’s a REAL and a user perceived performance for every application).</p>
<p>Nginx isn’t as well known and used as Apache’s HTTPD but one of the most common deployment environment for Rails applications (specially after Phusion Passenger for Nginx) we clearly needed a simple solution for this expires header. Looking a little bit over the internet you can usually find a code sample just like this one:</p>
<pre class="brush: plain;">location ~* \.(ico|css|js|gif|jpe?g|png)\?[0-9]+$ {
    expires max;
    break;
}</pre>
<p>Looking at the regex you can surely figure out that you’re going to match any asset that ends with any of those extensions and has a timestamp (“?123456”) at the end. The timestamps are usually added by Rails asset helpers and they’ll clean up your user’s browser cache when the file is changed (if there’s no timestamp the cache will be cleared only when it’s full or you change the static asset name).</p>
<p>All good, right? Not so easy, cowboy. If you try to use this location directive you’ll never match anything. You might then end up with the following solution:</p>
<pre class="brush: plain;">location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
    expires max;
    break;
}</pre>
<p>Now the timestamp is optional and you’ll finally start matching your static assets. But why wasn’t the previous directive working? Simple, the location directive will match only on the request filename, not on it’s query string. So, as there was never a timestamp, the first location would never set a far future expires header on anything. You should remove the timestamp match completely as it’s completely useless anyway.</p>
<p>But even this simple location directive has it’s own issues and they can easily bite you. We’re matching based on file extensions, so anything that ends with “.js” would be a match and would be served by Nginx, exactly what we want, right?</p>
<p>Maybe not. Imagine that you’re making a controller that responds to an HTML and an RJS view. The HTML view can be called by <strong>“/actions.html”</strong> and the RJS view can be called by <strong>“/actions.js”</strong>. When the browser calls <strong>“/actions.js”</strong>, Nginx looks at the extensions and thinks “hey, it’s a javascript file, I’ll handle it” and it sends a 404 error directly to your client, as this JS file doesn’t exist inside your public folder.</p>
<p>But you could use the HTTP request headers to tell your rails application that it’s a JS request, couldn’t you? Yep, but sometimes you can’t and you’d probably end up digging weird bugs and 404’s in production when you never saw them in your development machine. Not something really nice, I’d tell you.</p>
<p>And how do you get this sorted out? Instead of basing your rules in file extensions, you’ll do it using the folders where they live. In common Rails application images, javascript and stylesheet files have their own default folders and you would use a rule that matched on those folder names, just like the following:</p>
<pre class="brush: plain;">  location ~ ^/(images|javascripts|stylesheets|system)/  {
    expires max;
    break;
  }</pre>
<p>The system folder is usually where you keep user generated data, like uploaded images, documents and things alike. With this simple location directive you’ll get all benefits from static asset caching on Nginx without worrying about crazy errors in your application. If you don’t plan to write a controller that answers to <strong>“/stylesheets/my_custom_theme.css”</strong>, obviously.</p>
Posted in ruby Tagged: front end performance, nginx, rails <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/89/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/89/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/89/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=89&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/09/21/setting-a-far-future-expires-header-for-your-rails-app-static-assets-in-your-nginx-server/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
		<item>
		<title>Accessing the current request object on your mailer templates to generate links</title>
		<link>http://codeshooter.wordpress.com/2009/08/26/accessing-the-current-request-object-on-your-mailer-templates-to-generate-links/</link>
		<comments>http://codeshooter.wordpress.com/2009/08/26/accessing-the-current-request-object-on-your-mailer-templates-to-generate-links/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 13:16:52 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=86</guid>
		<description><![CDATA[A common issue with mailer templates is that as they’re not being called from a controller you can’t get your hands on the request object and access properties like host_with_port. While you’re usually calling the mailers inside controllers and you could possibly hand the request as a parameter to it, it isn’t really nice to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=86&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A common issue with mailer templates is that as they’re not being called from a controller you can’t get your hands on the request object and access properties like <strong>host_with_port</strong>. While you’re usually calling the mailers inside controllers and you could possibly hand the request as a parameter to it, it isn’t really nice to do this every time you need to send an email.</p>
<p>So, if you’re looking for a quick and easy solution to this issue, the <a href="http://github.com/mauricio/current_request/tree/master">current_request</a> plugin is your friend, you can install it by calling:</p>
<p><code>ruby script/plugin install git://github.com/mauricio/current_request.git</code></p>
<p>The plugin works by setting the current request in a thread local variable that will be available until the end of the request, which means that you can use it safely in your templates, two new methods are added to all views, <strong>current_request</strong>, that returns, obviously, the current request being answered and <strong>current_host</strong> that will build the current host with port and protocol for you. Examples:</p>
<pre class="brush: xml;">&lt; %= link_to 'Home', &quot;#{current_request.protocol}#{current_request.host_with_port}/home&quot; %&gt;</pre>
<p>Or you can just use a shorthand to the current host:</p>
<pre class="brush: xml;">&lt; %= link_to 'Home', &quot;#{current_host}/home&quot; %&gt;</pre>
<p>You can also use it wherever you want to access the current request (and not only on templates) by calling:</p>
<pre class="brush: ruby;">CurrentRequest::Holder.current_request</pre>
Posted in ruby, ruby on rails  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/86/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/86/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/86/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/86/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/86/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/86/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/86/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/86/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/86/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/86/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=86&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/08/26/accessing-the-current-request-object-on-your-mailer-templates-to-generate-links/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
		<item>
		<title>Why I am not using Masochism for my master-slave setups and why monkey-patching isn’t the only solution</title>
		<link>http://codeshooter.wordpress.com/2009/08/24/why-i-am-not-using-masochism-for-my-master-slave-setups-and-why-monkey-patching-isn%e2%80%99t-the-only-solution/</link>
		<comments>http://codeshooter.wordpress.com/2009/08/24/why-i-am-not-using-masochism-for-my-master-slave-setups-and-why-monkey-patching-isn%e2%80%99t-the-only-solution/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 17:02:20 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=74</guid>
		<description><![CDATA[I got a message this morning from Gregg at Ruby5 asking why I wrote the master_slave_adapter plugin instead of using Technoweenie’s Masochism and I think the answer to this question deserves a little blog post (and the blog really needs some new content :P).
When building the Talkies project we had to setup a master-slave environment [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=74&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I got a message this morning from Gregg at <a href="http://ruby5.envylabs.com/">Ruby5</a> asking why I wrote the <a href="http://github.com/mauricio/master_slave_adapter/tree">master_slave_adapter</a> plugin instead of using <a href="http://github.com/technoweenie/masochism/tree/master">Technoweenie’s Masochism</a> and I think the answer to this question deserves a little blog post (and the blog really needs some new content :P).</p>
<p>When building the <a href="http://talkies.de/">Talkies project</a> we had to setup a master-slave environment using MySQL at the production servers. To get these things up and running I configured the replication on MySQL and set out to find a solution on Rails/ActiveRecord to handle this special need, all SELECT* statements should be sent to the slave db while all other commands should be sent to the master. The only solution available at the time was Masochism (at least it was the only one I could find).</p>
<p>With Rails 2.1, everything looked like we would live happily ever after, but Rails 2.2 brought a lot of changes and many of them on ActiveRecord, the main one being connection pooling and we upgraded. The production server, that wasn’t really live yet, broke badly, the new connection pooling code made the application crazy and the slave was receiving UPDATE* and INSERT* calls ( <a href="http://github.com/technoweenie/masochism/blob/cccfa41154f28953944f063c9682a4a05308e861/lib/active_reload/connection_proxy.rb">this was the code at the moment</a> ).</p>
<p>With this new issue showing up I set out to find a solution, the first thing was to hack the plugin itself (as github had no “issues” thing at the moment). Trying it out I couldn’t really find a simple fix and wasn’t really happy with the way the plugin worked, looked a lot like a hack when a hack wasn’t really needed, so I started to write my own solution.</p>
<p>The first requirement was that it should perform no black magic at all, we were burned more than once during the project by plugins that were too clever and relied heavily on monkey-patching, so my solution had to be really straightforward and do as little clever things as possible. </p>
<p>But hey, active_record needs a database adapter, so why not just build a fake database adapter that forwarded the work to a master or slave connection depending on the method called? This way I would never need to hack ActiveRecord, as the thing would just be a common database adapter, like all the others and the plugin would survive to Rails upgrades with little or no changes. And that’s exactly what I did, an ActiveRecord database adapter who’s job is to route method calls to a real master or slave connection.</p>
<p>Why was it an improvement?</p>
<p>By relying on the ActiveRecord database adapter contract I had no need to monkey-patch Rails itself, it would just work, even if Rails or ActiveRecord got upgraded, the only thing that would make me change the plugin was if the database adapter contract got changed and this isn’t really something that changes a lot.</p>
<p>And if there’s one thing that’s burning a lot of people using plugins and Rails itself is clever code and too much monkey-patching. When you’re building a solution that’s going to be “inserted” inside someone else’s codebase that you don’t even know how it’s going to look like, you better try to avoid changing too many things or breaking well known contracts, you might end up with bugs that are hard to discover and kill. And they’ll surely make you waste a lot of your time.</p>
<p>Monkey-patching and class-redefinition are some of the coolest features of Ruby as a language, but they should be used with care and are better avoided if possible.</p>
Posted in ruby, ruby on rails  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/74/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=74&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/08/24/why-i-am-not-using-masochism-for-my-master-slave-setups-and-why-monkey-patching-isn%e2%80%99t-the-only-solution/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
		<item>
		<title>Setting up your Ruby on Rails application in an Ubuntu Jaunty Jackalope (9.04) server with Nginx, MySQL, Ruby Enterprise Edition and Phusion Passenger</title>
		<link>http://codeshooter.wordpress.com/2009/06/09/setting-up-your-ruby-on-rails-application-in-a-ubuntu-jaunty-jackalope-9-04-server-with-nginx-mysql-ruby-enterprise-edition-and-phusion-passenger/</link>
		<comments>http://codeshooter.wordpress.com/2009/06/09/setting-up-your-ruby-on-rails-application-in-a-ubuntu-jaunty-jackalope-9-04-server-with-nginx-mysql-ruby-enterprise-edition-and-phusion-passenger/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 17:11:05 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[deployment]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[nginx]]></category>
		<category><![CDATA[passenger]]></category>
		<category><![CDATA[ree]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=59</guid>
		<description><![CDATA[There are many ways to deploy and run Ruby applications with the Ruby on Rails framework but it’s unlikely that you’re going to find a simpler and faster solution than using Ruby Enterprise Edition (REE from now on) with Nginx and Phusion Passenger. Nginx is a fast, scalable and lightweight HTTP server, that is able [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=59&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>There are many ways to deploy and run Ruby applications with the Ruby on Rails framework but it’s unlikely that you’re going to find a simpler and faster solution than using <a href="http://rubyenterpriseedition.com/">Ruby Enterprise Edition</a> (REE from now on) with <a href="http://wiki.nginx.org/">Nginx</a> and <a href="http://www.modrails.com/">Phusion Passenger</a>. Nginx is a fast, scalable and lightweight HTTP server, that is able to serve a lot of content without using up all your memory and Passenger is a module that can be tied into Apache or Nginx to handle your Ruby (and RoR) applications automatically. </p>
<p>When using Passenger you don’t need to worry about managing a pack of Mongrels or use a proxy HTTP server, Passenger lives inside your web server and just takes care of everything for you. Here you’ll learn how to use Passenger in conjunction with Nginx to deploy your applications in the wild.</p>
<p>This tutorial assumes that you’re building a brand new Ubuntu server with none or little custom packages installed. Does this mean you can’t use this with an already customized server? No, but it’s easier if you can follow it step by step to avoid problems, as this has already been tried and tested to be sure that it works. We’re using MySQL here because it’s what I’m using right now but can easily change the apt-get calls to use whatever database you’re using yourself.</p>
<h2>Setting up users</h2>
<p>If you’re really starting up from a brand new install with no users created beyond the default ones you might want to create a user for yourself so that you don’t need to be logged in as a “root” forever. To create a new user in a Linux box the command is “useradd”:</p>
<p><code>useradd -m -g staff -s /bin/bash mauricio</code></p>
<p>This will create a user called “mauricio” with a “/home/mauricio” home directory (as defined by the “-m” param), with “staff” as it’s default group and using  the “/bin/bash” shell. After creating a user for yourself you might also want to create a user for the application you’re deploying or a “deployment” user. This is the user that’s going to be used to deploy the application and run all application related processes. Just use the same command above changing the username to your deploy user, this can be the name of the application you’re deploying or just “deploy” (keep all your users belonging to the same &#8220;staff&#8221; group to avoid file permission issues when you edit or create files).</p>
<p>After doing this you can also make all users that belong to the staff group be able to use the “sudo” command. To do this just open the “/etc/sudoers” file with a text editor (I usually use “nano”) and add this line:</p>
<p><code>%staff ALL=(ALL) ALL</code></p>
<h2>Setting up your ssh keys</h2>
<p>If you’re running in a Linux/Unix box and haven’t generated your SSH keys, it’s time to do it. If you have never heard of them, SSH keys can get you to login into servers where you have a user account without asking you for the password, which is really cool if you have to handle a lot of servers at the same time (and if you don’t want to type passwords every time you do a “git pull|git push”. To generate them do this as your local user in your local machine:</p>
<p><code>ssh-keygen -t dsa</code></p>
<p>This command will create a folder called “.ssh” in your home directory (as in “/home/your_user/.ssh” with a bunch of files. It will ask you for a password to protect these files,  the password isn’t required but it’s nice to be cautious here as if you don’t set a password anyone with physical access to your machine (or can log in as you) could log in into all machines to where your SSH keys were copied to.</p>
<p>Now that the keys are already generated, you can copy them to the servers you usually log into, to do this, first log in to the server using  your account and at your user’s home folder create a .ssh folder:</p>
<p><code>mkdir ~/.ssh</code></p>
<p>Log off and, from your local pc, copy the ~/.ssh/id_dsa.pub file to the remote machine using scp:</p>
<p><code>scp ~/.ssh/id_dsa.pub your_remote_user@host:.ssh/authorized_keys2</code></p>
<p>This will copy your public key to the remote server and you’ll be able to log into that server from your current local machine and local user to the user you copied the key to in your remote server. You can obviously copy this to as many servers and user accounts as you like and none of them will ask you for a password again.</p>
<h2>Getting Ubuntu up-to-date</h2>
<p>First thing we need to do is to be sure that our server is up-to-date with the currently installed software:</p>
<p><code>sudo apt-get update<br />
sudo apt-get upgrade</code></p>
<p>Then we need to install some basic libraries and MySQL:</p>
<p><code>sudo apt-get install build-essential mysql-server libmysqlclient15-dev libmagickcore-dev imagemagick  libpcre3 libfcgi-dev libfcgi0ldbl libxml2-dev libxslt1-dev -y</code></p>
<p>This is going to install the MySQL server, the ImageMagick library to handle image processing and the XML and XSLT libraries needed for some common gems like <a href="http://nokogiri.rubyforge.org/nokogiri/">Nokogiri</a>.</p>
<h2>Installing Ruby</h2>
<p>We’re not going to use the default Ruby interpreter that comes with Ubuntu but Phusions&#8217;s Ruby Enterprise Edition. REE is a reliable and memory friendly fork of the main Ruby interpreter from the Phusion guys. <a href="http://www.rubyenterpriseedition.com/download.html">Go to the REE download page</a> and grab the “.deb” files for your architecture (look for the “Ubuntu Linux” tab). Install the “.deb” with:</p>
<p><code>sudo dpkg -i path-to-the-deb-file</code></p>
<p>This will get REE installed to “/opt/ruby-enterprise” but the binaries will not be available at your PATH, we’ll need to add the “bin” dir to our PATH variable manually. Open up your “/etc/environment” file with your preferred command line text editor (mine is “nano”):</p>
<p><code>sudo nano /etc/environment</code></p>
<p>And add the “/opt/ruby-enterprise/bin” dir to your PATH variable like this:</p>
<p><code>PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/ruby-enterprise/bin"</code></p>
<p>This will get the scripts at the “bin” folder available to your user but not when you use “sudo” calls (Ubuntu just overrides the PATH when you call “sudo” for security reasons) so we’ll need to symlink some of the files to “/usr/bin” to be sure that they’re visible when you’re sudoing:</p>
<p><code>ln -s /opt/ruby-enterprise/bin/ruby     /usr/bin/ruby<br />
ln -s /opt/ruby-enterprise/bin/gem     /usr/bin/gem<br />
ln -s /opt/ruby-enterprise/bin/ri          /usr/bin/ri<br />
ln -s /opt/ruby-enterprise/bin/rdoc     /usr/bin/rdoc<br />
ln -s /opt/ruby-enterprise/bin/irb        /usr/bin/irb</code></p>
<p>Now let’s install some gems to be sure that everything is ok:</p>
<p><code>sudo gem install rails mysql nokogiri rmagick mislav-will_paginate --no-ri --no-rdoc</code></p>
<p>The “&#8211;no-ri &#8211;no-rdoc” option is to avoid creating docs that we’re not really going to use and that will take a long time to be generated (also, if you’re into a VPS and don’t have a lot of memory those commands are surely going to throw out of memory errors). If you got no errors here, we’re good to go and install Nginx and Passenger.</p>
<h2>Installing Nginx and Passenger</h2>
<p>Installing Nginx with Passenger and Ruby EE is as easy as calling this command:</p>
<p><code>sudo /opt/ruby-enterprise/bin/passenger-install-nginx-module --auto --auto-download</code></p>
<p>Those “&#8211;auto” options are there to tell the installer that we’re saying yes to all defaults and we want it to download a brand new Nginx copy and build it with the Passenger module.  The installer is going to ask you where to install Nginx with a default of “/opt/nginx”,  just hit enter to get it installed at the default path.</p>
<p>As you can see from the messages printed, Passenger has already generated a sample configuration file with the basic config needed to run the application,  <a href="http://gist.github.com/126659">here’s an example of how it would look like</a>.</p>
<p>It’s VERY important to set the Nginx user to be the same user that’s going to deploy and create the application files as this will avoid permission issues that are one of the most common problems you&#8217;re going to have. With Nginx configured to load your application, start it to be sure that everything is OK again:</p>
<p><code>sudo /opt/nginx/sbin/nginx</code></p>
<p>Open up your browser pointing to the server where Nginx is running and you should see your application running correctly. If it isn’t, check the application logs and also Nginx error logs at “/opt/nginx/logs/error.log”. You can kill Nginx with a simple:</p>
<p><code>sudo pkill nginx</code></p>
<h2>Getting Nginx to run as a Daemon</h2>
<p>Now that Nginx is running correctly and serving your application you need to set it up to run as a daemon. To do this we need to create a script that’s going to handle the Nginx daemon and install it using the update-rc.d utility. You can get the script <a href="http://gist.github.com/126656">here</a>.</p>
<p>You should save this script at “/etc/init.d/nginx” (sudo to do it), mark it as executable and install it as a daemon:</p>
<p><code>sudo chmod +x /etc/init.d/nginx<br />
sudo update-rc.d nginx defaults</code></p>
<p>Now when the machine reboots Nginx will be started automatically. As a last touch, start the Nginx daemon and your server is ready to roll:</p>
<p><code>sudo /etc/init.d/nginx start</code></p>
Posted in ruby, ruby on rails Tagged: deployment, linux, nginx, passenger, ree, ruby, ruby on rails <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/59/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=59&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/06/09/setting-up-your-ruby-on-rails-application-in-a-ubuntu-jaunty-jackalope-9-04-server-with-nginx-mysql-ruby-enterprise-edition-and-phusion-passenger/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
		<item>
		<title>Quick Tip – Using to_s as a label and simplified link_to calls to your ActiveRecord models</title>
		<link>http://codeshooter.wordpress.com/2009/06/08/quick-tip-using-to_s-as-a-label-and-simplified-link_to-calls-to-your-activerecord-models/</link>
		<comments>http://codeshooter.wordpress.com/2009/06/08/quick-tip-using-to_s-as-a-label-and-simplified-link_to-calls-to-your-activerecord-models/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 03:27:29 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=53</guid>
		<description><![CDATA[One of the things you’ll find in every rails application is links like this one:
&#60; %= link_to user.login, user %&#62;
Or maybe like this one:
&#60; %= link_to user.login, user_path( user ) %&#62;
Or maybe something ugly like this one:
&#60; %= link_to user.to_label, user_path( user ) %&#62;
How about throwing all of them and just doing it like this:
&#60; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=53&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>One of the things you’ll find in every rails application is links like this one:</p>
<pre class="brush: xml;">&lt; %= link_to user.login, user %&gt;</pre>
<p>Or maybe like this one:</p>
<pre class="brush: xml;">&lt; %= link_to user.login, user_path( user ) %&gt;</pre>
<p>Or maybe something ugly like this one:</p>
<pre class="brush: xml;">&lt; %= link_to user.to_label, user_path( user ) %&gt;</pre>
<p>How about throwing all of them and just doing it like this:</p>
<pre class="brush: xml;">&lt; %= link_to user %&gt;</pre>
<p>Cool, isn’t it?</p>
<p>Now “how can I do that” you ask, it’s dead simple. First, remember that every object responds to a method called “to_s” and this “to_s” method is defined as “a method that returns a string representation of your object” in most programming languages, including Ruby.</p>
<p>A string representation of your object is something human readable that would tell someone else what this object represents. “to_s” isn’t meant to be a debug like method, we already have “inspect” to do that, so why not put it to work and simplify our links?</p>
<p>At every ActiveRecord model in your application you’ll define a to_s method that returns one (or maybe more, if needed) attributes of your object as a string (if they’re not strings, turn them into strings and return). Let’s see how your user would look like:</p>
<pre class="brush: ruby;">class User &lt; ActiveRecord::Base
    validates_presence_of :login
    validates_uniqueness_of :login
    def to_s
        self.login
    end
end</pre>
<p>I decided that the &#8220;login&#8221; method is the one that best represents the User object and it&#8217;s also the one I want to use then someone else seers users on the website. They won&#8217;t see their real names by default, but their logins.</p>
<p>Why is it better to do this with the &#8220;to_s&#8221; method instead of adding a “to_label” method to all objects? ‘Cos many helpers will already call the to_s method by default on your object (as we&#8217;ll see with the link_to helper), so you just get full compatibility for free. Check out our new link_to implementation:</p>
<pre class="brush: ruby;">module ApplicationHelper
  #sample link_to override that will generate urls for active_record objects by default
  #if the first parameter is an active_record object and you just want a link to it,
  # you can call it just like this:
  # &lt;%= link_to user %&gt;
  # the helper will take care of generating the correct url
  def link_to( *args )
    options = args.extract_options!
    if args.size == 1 &amp;&amp; args.first.is_a?( ActiveRecord::Base )
      super( *([ args.first, args.first ] + [ options ]) )
    else
      super( *( args + [ options ] ) )
    end
  end
end</pre>
<p>If there’s only one object (besides the options hash) and it is an ActiveRecord::Base instance, just use the object itself as the url parameter (the real link_to helper will call polymorphic_url on it automatically) and also use the object as the link_to label (the first parameter), this will call the to_s method on our user and the link will use it as the label.</p>
<p>What do you get with this?</p>
<p>A seamless and clear way of defining labels for your models (the “to_s” method is part of the core of the language anyway) and also a simpler way of generating links for your objects. Common methods for object labels are very important because you can never be sure if the property you’re using today as a label will be used forever. Using the “to_s” method as the default “label method” will allow you to change the label property at any time with almost no change to other parts of the code.</p>
Posted in ruby, ruby on rails Tagged: rails, ruby, tips <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/53/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/53/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/53/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=53&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/06/08/quick-tip-using-to_s-as-a-label-and-simplified-link_to-calls-to-your-activerecord-models/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
		<item>
		<title>Building a I18N aware form builder for your Rails applications</title>
		<link>http://codeshooter.wordpress.com/2009/06/06/building-a-i18n-aware-form-builder-for-your-rails-applications/</link>
		<comments>http://codeshooter.wordpress.com/2009/06/06/building-a-i18n-aware-form-builder-for-your-rails-applications/#comments</comments>
		<pubDate>Sat, 06 Jun 2009 13:21:18 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[form builder]]></category>
		<category><![CDATA[i18n]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=45</guid>
		<description><![CDATA[Form builders are one of the coolest features when building Rails applications, they streamline the task of writing complex forms and you can usually write your own form builder to maintain their consistency in your application. One of the most common customized form builders is the one that users the field name to show a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=45&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Form builders are one of the coolest features when building Rails applications, they streamline the task of writing complex forms and you can usually write your own form builder to maintain their consistency in your application. One of the most common customized form builders is the one that users the field name to show a label:</p>
<pre class="brush: xml;">&lt; % form_for @user, :builder =&gt; SimpleFormBuilder do |f| %&gt;
    &lt; %= f.text_field :date_of_birth %&gt;
&lt; % end %&gt;</pre>
<p>We would probably use the “date_of_birth” symbol, turn it into a String and then call “humanize” on it ( you can see a custom form builder example that does exactly this <a href="http://onrails.org/articles/2008/06/13/advanced-rails-studio-custom-form-builder">here</a> ):</p>
<pre class="brush: ruby;">:date_of_birth.to_s.humanize
=&gt; “Date of birth”</pre>
<p>That’s awesome if you’re building a website for a language that uses only ASCII characters, but if you’re building a form in Portuguese you’re doomed. Imagine that my “usuario” (user) has a “profissão” (profession) and I try to use it using a common form builder:</p>
<pre class="brush: xml;">&lt; % form_for @usuario, :builder =&gt; SimpleFormBuilder do |f| %&gt;
    &lt; %= f.text_field :profissao %&gt;
&lt; % end %&gt;</pre>
<p>What do I get? “profissao”, no tilde. And if I try to create a method called “profissão” at my object it’s just going to break. </p>
<p>So, customized form builders for Rails using funny characters are impossible? Never! With the new I18N support this trouble as been completely removed, let’s see how we can write a customized form builder that uses the attribute names to generate labels and will respect funny Portuguese, Russian or characters from any other language.</p>
<p>Here’s the builder code:</p>
<pre class="brush: ruby;">class SimpleFormBuilder &lt; ActionView::Helpers::FormBuilder

  attr_accessor :object_class

  helpers = field_helpers +
            %w{date_select datetime_select time_select} +
            %w{collection_select select country_select time_zone_select} -
            %w{hidden_field label fields_for submit select} # Don't decorate these

  helpers.each do |name|
    class_eval %Q!
    def #{name}(field, *args)
      options = args.extract_options\!
      args &lt;&lt; options
      return super if options.delete(:disable_builder)
      @template.content_tag(:p, field_label(field, options) &lt;&lt; '&lt;br/&gt;' &lt; &lt; super)
    end
    !
  end

  def select(field, choices, options = {}, html_options = {})
    return super if options.delete(:disable_builder) || html_options.delete(:disable_builder)
    @template.content_tag(:p, [field_label(field, options), '&lt;br/&gt;', super].join(&quot;\n&quot;))
  end

  def submit(value = nil, options = {})
    if self.object &amp;&amp; value.nil?
      value = self.object.new_record? ? I18n.t( 'txt.shared.create' ) : I18n.t( 'txt.shared.update' )
    end
    @template.content_tag( :p, super( value, options ) )
  end

  def field_label( field, options )
    self.label( field, options.delete( :label ) || self.object_class.human_attribute_name( field.to_s ), :class =&gt; options[:label_class])
  end

  def initialize(object_name, object, template, options, proc)
    super
    self.object_class = self.object.nil? ? self.object_name.to_s.camelize.constantize : self.object.class
  end

end</pre>
<p>We’ve created our own form builder that inherits from the ActionView::Helpers::FormBuilder and it redefines all field helpers using a class_eval call (don’t know what class_eval does? <a href="http://codeshooter.wordpress.com/2009/06/04/understanding-class_eval-module_eval-and-instance_eval/">Learn here</a>).</p>
<p>Our version isn’t really that different from the usual solution, it looks for a :disable_builder option, if there’s one and it’s true, the builder will just call the original method, without the custom decoration. If there’s no :disable_builder option the builder will set out to do its work. Also, we need the object class to find out the correct attribute names, so your form builder also holds the class of the object that’s being used in the form.</p>
<p>If there’s a :label option available, it’s the one that’s going to be used, if there’s no :label option the builder will access the class of the object that’s being used in the form and call the “human_attribute_name” with the field name as a parameter on it. By default, “human_attribute_name” will just call “humanize” on your field name (same as our code above) but, when we’re using the Rails I18N support things change a bit.</p>
<p>The first thing that changes is that we can use the I18N support to define labels for those fields (and also for the class names). Let’s take a look at the “config/locale/en.yml” to check out how it looks like:</p>
<pre class="brush: ruby;">en:
  activerecord:
    models:
      user:
        one: User
        other: Users
    attributes:
      user:
        name: Name
        date_of_birth: Date of birth
        login: Login
        password: Password
        password_confirmation: Confirm Password
        profession: Profession</pre>
<p>Under the “activerecord” namespace we have the “models” and “attributes” namespaces. As you might have guessed, the “models” namespace is used to internationalize your model names and the “attributes” to do the same to your object’s attribute names. While we’re using English as the language things aren’t really that interesting, so we’re going to add Portuguese support:</p>
<pre class="brush: ruby;">pt-BR:
  activerecord:
    models:
      user:
        one: Usuário
        other: Usuários
    attributes:
      user:
        name: Nome
        date_of_birth: Data de Nascimento
        login: Login
        password: Senha
        password_confirmation: Confirmação da Senha
        profession: Profissão</pre>
<p>And now your form builder will use the Portuguese field names on its labels whenever the current locale is set to “pt-BR” (this isn’t the full file, you can check it out at the project repo). The real catch here is to use the “human_attribute_name” instead of just “humanizing“ the field name.</p>
<p>When human_attribute_name is called it will first try to get the attribute name from your I18N files using the current locale and you don’t really need to be writing a Multilanguage application to use the I18N support, whenever you’re using a language that isn’t pure ASCII only you can use the I18N support and have nice default labels for your form fields. Translating your models using the default “models” and “attributes” namespaces will also internationalize Rails default error messages, as they’re going to use the names of the current locale.</p>
<p>You can see this form builder in action at the <a href="https://github.com/mauricio/sample_social_network/tree">sample_social_network project</a>.</p>
Posted in ruby, ruby on rails, Tutorials Tagged: form builder, i18n, rails, ruby <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/45/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=45&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/06/06/building-a-i18n-aware-form-builder-for-your-rails-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
		<item>
		<title>Understanding class_eval, module_eval and instance_eval</title>
		<link>http://codeshooter.wordpress.com/2009/06/04/understanding-class_eval-module_eval-and-instance_eval/</link>
		<comments>http://codeshooter.wordpress.com/2009/06/04/understanding-class_eval-module_eval-and-instance_eval/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 02:53:30 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=39</guid>
		<description><![CDATA[Most of Ruby’s fame is due to it’s dynamic capabilities. In Ruby you can define and redefine methods at runtime, create classes from nowhere and objects from pure dust. Most of these dynamical features are done using one of those methods at the title, class_eval, module_eval and instance_eval, they’re usually the ones responsible for the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=39&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Most of Ruby’s fame is due to it’s dynamic capabilities. In Ruby you can define and redefine methods at runtime, create classes from nowhere and objects from pure dust. Most of these dynamical features are done using one of those methods at the title, class_eval, module_eval and instance_eval, they’re usually the ones responsible for the show and now we’re going to learn a little bit about how they work and how we could use them in our objects.</p>
<h2>class_eval and module_eval</h2>
<p>These two methods are responsible to granting your access to a class or module definition, as if you were writing their code by yourself. When you do something like this:</p>
<pre class="brush: ruby;">Dog.class_eval do
    def bark
        puts “Huf! Huf! Huf!”
    end
end</pre>
<p>It’s almost the same as doing this:</p>
<pre class="brush: ruby;">class Dog
    def bark
        puts “Huf! Huf! Huf!”
    end
end</pre>
<p>What’s the difference?</p>
<p>With the class_eval you’re adding a method to a pre-existing class. If a class called Dog is not defined before our class_eval runs you’d see an “NameError: uninitialized constant Dog”. A class_eval call opens up an existing class for you, it won’t create or open a class that doesn’t exist yet.</p>
<p>And you don’t need to always write real code inside your class_eval calls, you can also send a string object containing the code you want to have ‘evaled inside your class. Let’s see how we could define a macro just like the attr_accessor using class_eval’ed strings:</p>
<pre class="brush: ruby;">Object.class_eval do

  class &lt; &lt; self

    def attribute_accessor( *attribute_names )

      attribute_names.each do |attribute_name|
        class_eval %Q?
          def #{attribute_name}
              @#{attribute_name}
          end

          def #{attribute_name}=( new_value )
              @#{attribute_name} = new_value
          end
        ?
      end

    end

  end

end

class Dog
  attribute_accessor :name
end

dog = Dog.new
dog.name = 'Fido'

other_dog = Dog.new
other_dog.name = 'Dido'

puts dog.name
puts other_dog.name</pre>
<p>As you can see, we used both kinds of class_eval. First we opened up the Object class and added a new class method called attribute_accessor with direct code, but then, at the attribute_acessor I had no way to figure out the method name when I was writing the code, so, instead of just writing the code directly inside the class_eval call I’ve created a string object containing the code that I wanted to have ‘evaled by the class_eval method. The string is then turned into something like this:</p>
<pre class="brush: ruby;">def name
    @name
end

def name=( new_value )
    @name = new_value
end</pre>
<p>And this is the parameter passed on to the class_eval call. Wrapping up, you can use class_eval to open classes (and modules) and add real code on it as you also can just pass a string containing valid Ruby code and it’s going to be ‘evaled as it was at the class definition body.</p>
<p>The module_eval method is just an alias to class_eval so you can use them both for classes and modules.</p>
<p>The instance_eval method works just like class_eval but it will add the behavior you’re trying to define to the object instance where it was called. </p>
<p>But hey, isn’t this exactly what we were doing with class_eval?</p>
<p>No, it isn’t. With class_eval we opened up a class definition and added code to it’s body. Any kind of code valid inside a class definition was also valid in there. When we’re using instance_eval the rules change a bit ‘cos we’re not opening up a class, but a single object instance.</p>
<p>How’s that? Let’s see an example:</p>
<pre class="brush: ruby;">class Dog
  attribute_accessor :name
end

dog = Dog.new
dog.name = 'Fido'

dog.instance_eval do
    #here I am defining a bark method only for this “dog” instance and not for the Dog class
  def bark
   puts 'Huf! Huf! Huf!'
  end

end

other_dog = Dog.new
other_dog.name = 'Dido'

puts dog.name
puts other_dog.name

dog.bark
other_dog.bark #this line will raise a NoMethodError as there’s no “bark” method
                      #at this other_dog object</pre>
<p>Not really that interesting, is it? We can also use instance_eval to define methods in Class objects (which in turn will be class methods at that Class object instances) and we can do just that to our attribute_accessor:</p>
<pre class="brush: ruby;">Object.instance_eval do

  def attribute_accessor( *attribute_names )

    attribute_names.each do |attribute_name|
      class_eval %Q?
          def #{attribute_name}
              @#{attribute_name}
          end

          def #{attribute_name}=( new_value )
              @#{attribute_name} = new_value
          end
      ?
    end

  end

end</pre>
<p>By using instance_eval instead of class_eval we don’t need the “class &lt;&lt; self” as the method is defined directly at the Object class and will then be available as a class method for Object instances and Object subclasses instances. </p>
<p>As you might have noticed, <a href="http://codeshooter.wordpress.com/2008/09/27/including-and-extending-modules-in-ruby/">these methods are also related to the difference between including and extending modules in Ruby.</p>
Posted in ruby Tagged: metaprogramming, reflection, ruby <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/39/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=39&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/06/04/understanding-class_eval-module_eval-and-instance_eval/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
		<item>
		<title>with_scope and named_scopes ignoring stacked :order clauses</title>
		<link>http://codeshooter.wordpress.com/2009/06/04/with_scope-and-named_scopes-ignoring-stacked-order-clauses/</link>
		<comments>http://codeshooter.wordpress.com/2009/06/04/with_scope-and-named_scopes-ignoring-stacked-order-clauses/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 22:03:00 +0000</pubDate>
		<dc:creator>Maurício Linhares</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://codeshooter.wordpress.com/?p=33</guid>
		<description><![CDATA[If you&#8217;ve been using with_scope and named_scopes a lot with ActiveRecord you have probably noticed that the :order clauses defined at the scopes are lost and only the first :order clause is used. If you defined an :order clause you&#8217;d like to have it merged with the other ones already provided. Here&#8217;s a simple example:
class [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=33&subd=codeshooter&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>If you&#8217;ve been using with_scope and named_scopes a lot with ActiveRecord you have probably noticed that the :order clauses defined at the scopes are lost and only the first :order clause is used. If you defined an :order clause you&#8217;d like to have it merged with the other ones already provided. Here&#8217;s a simple example:</p>
<pre class="brush: ruby;">class User
  named_scope :by_first_name, :order =&gt; &quot;#{quoted_table_name}.first_name ASC&quot;
  named_scope :by_last_name, :order =&gt; &quot;#{quoted_table_name}.last_name ASC&quot;
end</pre>
<p>Our user has two named scopes defined and both of them define an :order clause, if we try to run a finder like this:</p>
<pre class="brush: ruby;">User.by_first_name.by_last_name.all</pre>
<p>This is the generated query:</p>
<pre class="brush: sql;">SELECT * FROM `users` ORDER BY `users`.first_name ASC</pre>
<p>As you&#8217;ve noticed, only the first :order clause was used, the last one was lost. Our ideal SQL query would have to look like this, with both :order clauses being used:</p>
<pre class="brush: sql;">SELECT * FROM `users` ORDER BY `users`.last_name ASC , `users`.first_name ASC</pre>
<p>That&#8217;s why we&#8217;re going to hack the with_scope method a litle bit to reach our goal. This issue <a href="https://rails.lighthouseapp.com/projects/8994/tickets/2253-named_scope-and-nested-order-clauses">was already reported to the Rails issue tracker</a> but there&#8217;s no fix yet so our only hope is to monkeypatch Rails to behave as we expect it to, so here&#8217;s a really simple fix for the problem:</p>
<pre class="brush: ruby;">ActiveRecord::Base.class_eval do

  class &lt;&lt; self

    def merge_orders( *orders )
      orders.map! do |o|
        if o.blank?
          nil
        else
          o.strip!
          o
        end
      end
      orders.compact!
      orders.join( ' , ' )
    end

    def with_scope_with_hack(method_scoping = {}, action = :merge, &amp;block)
      method_scoping = method_scoping.method_scoping if method_scoping.respond_to?(:method_scoping)

      # Dup first and second level of hash (method and params).
      method_scoping = method_scoping.inject({}) do |hash, (method, params)|
        hash[method] = (params == true) ? params : params.dup
        hash
      end

      method_scoping.assert_valid_keys([ :find, :create ])

      if f = method_scoping[:find]
        f.assert_valid_keys(VALID_FIND_OPTIONS)
        set_readonly_option! f
      end

      # Merge scopings
      if [:merge, :reverse_merge].include?(action) &amp;&amp; current_scoped_methods
        method_scoping = current_scoped_methods.inject(method_scoping) do |hash, (method, params)|
          case hash[method]
          when Hash
            if method == :find
              (hash[method].keys + params.keys).uniq.each do |key|
                merge = hash[method][key] &amp;&amp; params[key] # merge if both scopes have the same key
                if key == :conditions &amp;&amp; merge
                  if params[key].is_a?(Hash) &amp;&amp; hash[method][key].is_a?(Hash)
                    hash[method][key] = merge_conditions(hash[method][key].deep_merge(params[key]))
                  else
                    hash[method][key] = merge_conditions(params[key], hash[method][key])
                  end
                elsif key == :include &amp;&amp; merge
                  hash[method][key] = merge_includes(hash[method][key], params[key]).uniq
                elsif key == :joins &amp;&amp; merge
                  hash[method][key] = merge_joins(params[key], hash[method][key])
                elsif key == :order &amp;&amp; merge
                  hash[method][key] = merge_orders(params[key], hash[method][key])
                else
                  hash[method][key] = hash[method][key] || params[key]
                end
              end
            else
              if action == :reverse_merge
                hash[method] = hash[method].merge(params)
              else
                hash[method] = params.merge(hash[method])
              end
            end
          else
            hash[method] = params
          end
          hash
        end
      end

      self.scoped_methods &lt;&lt; method_scoping
      begin
        yield
      ensure
        self.scoped_methods.pop
      end
    end

    alias_method_chain :with_scope, :hack

  end

end</pre>
<p>You can place this code at an initializer (maybe called with_scope_fix.rb) or at your lib folder and require it in your initializers. And now all your :order clauses defined by named_scope or with_scope calls will be correctly merged and will not be lost in your code.</p>
Posted in ruby, ruby on rails  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codeshooter.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codeshooter.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codeshooter.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codeshooter.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codeshooter.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codeshooter.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codeshooter.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codeshooter.wordpress.com/33/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codeshooter.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codeshooter.wordpress.com/33/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codeshooter.wordpress.com&blog=2092185&post=33&subd=codeshooter&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://codeshooter.wordpress.com/2009/06/04/with_scope-and-named_scopes-ignoring-stacked-order-clauses/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1426a9fd5267e73d9e30ebaac1bde144?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">Maurício Linhares</media:title>
		</media:content>
	</item>
	</channel>
</rss>