<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>paulsturgess.co.uk articles</title>
    <link>http://www.paulsturgess.co.uk/articles</link>
    <description>paulsturgess.co.uk Ruby on Rails articles</description>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/paulsturgesscouk" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="paulsturgesscouk" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
      <title>How to set the value of a field directly using Capybara</title>
      <link>http://www.paulsturgess.co.uk/articles/show/104-how-to-set-the-value-of-a-field-directly-using-capybara?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;One of the most obvious ways your website can be attacked is through a form being maliciously tampered with.&lt;/p&gt;

&lt;p&gt;To cover this scenario in integration tests, using Capybara, it is possible to manually set the value of a field (even if it is a hidden field) with the following:&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;find("#your_field_id").set "malicious_value"&lt;/code&gt;&lt;/pre&gt;</description>
      <guid>http://www.paulsturgess.co.uk/articles/show/104-how-to-set-the-value-of-a-field-directly-using-capybara?action=show&amp;controller=articles</guid>
    </item>
    <item>
      <title>How to reset the primary key sequence for a table in Ruby on Rails</title>
      <link>http://www.paulsturgess.co.uk/articles/show/103-how-to-reset-the-primary-key-sequence-for-a-table-in-ruby-on-rails?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;Sometimes when importing data the primary key sequence can get messed up. I've come across this more often with PostgreSQL databases.&lt;/p&gt;

&lt;p&gt;Anyway, an easy way to reset the key in Rails is via:&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;ActiveRecord::Base.connection.reset_pk_sequence!('table_name')&lt;/code&gt;&lt;/pre&gt;
</description>
      <guid>http://www.paulsturgess.co.uk/articles/show/103-how-to-reset-the-primary-key-sequence-for-a-table-in-ruby-on-rails?action=show&amp;controller=articles</guid>
    </item>
    <item>
      <title>Installing Capistrano on Ruby 1.8.6 – Abort Trap error</title>
      <link>http://www.paulsturgess.co.uk/articles/show/102-installing-capistrano-on-ruby-186-abort-trap-error?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;Occasionally when installing gems I'll get an &lt;code&gt;abort trap&lt;/code&gt; failure message.&lt;/p&gt;

&lt;p&gt;Often I've found this means the version of Ruby isn't compatible with the gem. Sometimes I'll strike lucky and they'll be another version of the gem that does work.&lt;/p&gt;

&lt;p&gt;However, that isn't always the case and there are times when it's not the version of Ruby that's the problem. Specifically I've seen this happen when installing Capistrano on Ruby 1.8.6&lt;/p&gt;

&lt;p&gt;The way round this is simply to install the &lt;code&gt;Highline&lt;/code&gt; gem first. To be honest I can't remember how I figured this out but it works for me. Hope it saves someone out there some time if they hit the same problem.&lt;/p&gt;

</description>
      <guid>http://www.paulsturgess.co.uk/articles/show/102-installing-capistrano-on-ruby-186-abort-trap-error?action=show&amp;controller=articles</guid>
    </item>
    <item>
      <title>How to retry a specific queue of failed Resque jobs  </title>
      <link>http://www.paulsturgess.co.uk/articles/show/101-how-to-retry-a-specific-queue-of-failed-resque-jobs-?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;Resque has a very handy interface for managing the queue of jobs but it falls short when jobs fail.&lt;/p&gt;

&lt;p&gt;In order to only retry a specific queue drop onto the command line and run the following...&lt;/p&gt;
 
&lt;pre&gt;&lt;code class="ruby"&gt;jobs = Resque::Failure.all(0, X)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Where X is the total number of failed messages.&lt;/p&gt;
&lt;pre&gt;&lt;code class="ruby"&gt;jobs.each_with_index {|j,i| Resque::Failure.requeue(i) if j["queue"] == "queue_name" }&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It's important you loop around all the jobs, filtering inside the loop, as the &lt;code&gt;requeue&lt;/code&gt; method relies on the index being accurate so it retries the correct job.&lt;/p&gt;

&lt;p&gt;Note that as each job is retried it wont clear the failed job out. You'll know if the job is successful, however, if your failed jobs list doesn't grow.&lt;/p&gt;   
</description>
      <guid>http://www.paulsturgess.co.uk/articles/show/101-how-to-retry-a-specific-queue-of-failed-resque-jobs-?action=show&amp;controller=articles</guid>
    </item>
    <item>
      <title>Heroku H14 error (No Web Process running)</title>
      <link>http://www.paulsturgess.co.uk/articles/show/100-heroku-h14-error-no-web-process-running?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;Recently I had this problem even though &lt;code&gt;heroku ps&lt;/code&gt; said everything was up and running and I had one web worker running.&lt;/p&gt;

&lt;p&gt;However, a quick turn it off and on again and everything was good:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;heroku restart&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Heroku have a &lt;a href="http://devcenter.heroku.com/articles/error-codes"&gt;detailed list of error codes and solutions&lt;/a&gt; that are well worth a look at.&lt;/p&gt;



</description>
      <guid>http://www.paulsturgess.co.uk/articles/show/100-heroku-h14-error-no-web-process-running?action=show&amp;controller=articles</guid>
    </item>
    <item>
      <title>How to write a ruby gem</title>
      <link>http://www.paulsturgess.co.uk/articles/show/99-how-to-write-a-ruby-gem?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;Did you know you can use &lt;a href="http://gembundler.com/"&gt;Bundler&lt;/a&gt; to create gems?&lt;/p&gt;

&lt;p&gt;This guide aptly named &lt;a href="https://github.com/radar/guides/blob/master/gem-development.md"&gt;'Developing a RubyGem using Bundler'&lt;/a&gt; is quite comprehensive and well worth a read.&lt;/p&gt;

&lt;p&gt;Additionally the &lt;a href="http://guides.rubygems.org/"&gt;guides on rubygems.org&lt;/a&gt; are great. The &lt;a href="http://guides.rubygems.org/make-your-own-gem/"&gt;'Make your own gem'&lt;/a&gt; in particular.&lt;/p&gt;

&lt;p&gt;Any gems on rubygems.org are automatically documented online by &lt;a href="http://yardoc.org"&gt;YARD&lt;/a&gt;.&lt;/p&gt;</description>
      <guid>http://www.paulsturgess.co.uk/articles/show/99-how-to-write-a-ruby-gem?action=show&amp;controller=articles</guid>
    </item>
    <item>
      <title>ActiveRecord::StatementInvalid Mysql::Error: Duplicate entry in Ruby on Rails</title>
      <link>http://www.paulsturgess.co.uk/articles/show/98-activerecordstatementinvalid-mysqlerror-duplicate-entry-in-ruby-on-rails?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;Sometimes users like to double click, sometimes requests just happen very, very, very close together. This can mean that Rails isn't quick enough to use the validations you have setup in your models to prevent duplicate entries getting into the database. I've found ajax requests are particularly vulnerable.&lt;/p&gt;

&lt;p&gt;So like all good programmers the database is setup with unique indexes and the like to ensure that, regardless of the client connecting to the database, your data stays clean.&lt;/p&gt;

&lt;p&gt;However, this can sometimes cause annoying Duplicate entry exceptions that actually, you don't really care about and you'd just wish your application silently captured them.&lt;/p&gt;

&lt;p&gt;A few times now I've implemented code like this...&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;begin
  SomeObject.create(...)
rescue ActiveRecord::StatementInvalid =&gt; e
  raise e unless /#{DUPLICATE_ENTRY_ERROR}/.match(e)
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then in an intializer I have... &lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;DUPLICATE_ENTRY_ERROR = "Mysql::Error: Duplicate entry"&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I don't like it but it does work. Another option could be to use javascript to disable form buttons after the initial submit but this felt like a more 'fool proof' method.&lt;/p&gt;

&lt;p&gt;I'm all up for hearing any alternative suggestions, so if you know a better solution please leave a comment.&lt;/p&gt;</description>
      <guid>http://www.paulsturgess.co.uk/articles/show/98-activerecordstatementinvalid-mysqlerror-duplicate-entry-in-ruby-on-rails?action=show&amp;controller=articles</guid>
    </item>
    <item>
      <title>How to remove a specific version of a gem file in a specific directory</title>
      <link>http://www.paulsturgess.co.uk/articles/show/97-how-to-remove-a-specific-version-of-a-gem-file-in-a-specific-directory?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;First find the path of the gem...&lt;/p&gt;
&lt;pre&gt;&lt;code class="ruby"&gt;gem list -d "name_of_gem"&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then to remove the gem...&lt;/p&gt;
&lt;pre&gt;&lt;code class="ruby"&gt;gem uninstall 'name_of_gem' -i '/path/to/gem'&lt;/code&gt;&lt;/pre&gt;</description>
      <guid>http://www.paulsturgess.co.uk/articles/show/97-how-to-remove-a-specific-version-of-a-gem-file-in-a-specific-directory?action=show&amp;controller=articles</guid>
    </item>
    <item>
      <title>Ruby on Rails to_sym ArgumentError: interning empty string on startup </title>
      <link>http://www.paulsturgess.co.uk/articles/show/96-ruby-on-rails-to_sym-argumenterror-interning-empty-string-on-startup-?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;Recently when I deployed a Rails application onto the staging server I got a Passenger error page telling me the application wouldn't start. The full error was:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/var/lib/gems/1.8/gems/actionpack-2.3.5/lib/action_view/template.rb:226:in `to_sym':ArgumentError: interning empty string&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Essentially it's saying you can't call to_sym on an empty string. Unfortunately no great clues as to why this might be happening.&lt;/p&gt;

&lt;p&gt;Looking at the backtrace revealed the source of issue was triggered by the &lt;code&gt;valid_locale?&lt;/code&gt; method in &lt;code&gt;Action View&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Such is the beauty of Rails I've never really had the need to delve into this method before to see what's going on. However, after a bit of digging I could see that Rails checks all the extensions of the view files to determine the language. Clever.&lt;/p&gt;

&lt;p&gt;So I stuck in a simple rescue around the method call and output the full path of the file it was running this method on. This revealed the problem,  a file had been checked into the repository, unknown to me, that had a filename in the format:&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;foo..html.erb&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I removed the extra period and everything worked. I hope this saves someone out there the time I wasted hunting this down!&lt;/p&gt;  </description>
      <guid>http://www.paulsturgess.co.uk/articles/show/96-ruby-on-rails-to_sym-argumenterror-interning-empty-string-on-startup-?action=show&amp;controller=articles</guid>
    </item>
    <item>
      <title>Autocomplete text input using unobtrusive jQuery in Ruby on Rails</title>
      <link>http://www.paulsturgess.co.uk/articles/show/95-autocomplete-text-input-using-unobtrusive-jquery-in-ruby-on-rails?action=show&amp;controller=articles</link>
      <description>&lt;p&gt;Recently I needed to implement an autocomplete feature into a Ruby on Rails application so I thought I'd throw up the bare-bones of what I came up with as a simple example.&lt;/p&gt;

&lt;p&gt;Note that it written unobtrusively using jQuery, but as it was for an admin system there is no non-javascript fall back.&lt;/p&gt;

&lt;p&gt;So for my example we have groups and in those groups we have multiple users (joined by a group_users table). I want to be able to create a group and add all the users on one screen, using autocomplete to find the users.&lt;/p&gt;

&lt;p&gt;The models...&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;class Group &lt; ActiveRecord::Base
  has_many :group_users, :dependent =&gt; :destroy
  has_many :users, :through =&gt; :group_users
end

class GroupUser &lt; ActiveRecord::Base
  belongs_to :group
  belongs_to :user
end

class User &lt; ActiveRecord::Base
  has_many :group_users
  has_many :groups, :through =&gt; :group_users
  
  named_scope :autocomplete_name, lambda{ |name| {:include =&gt; :user, :conditions =&gt; ["users.name LIKE ?", "#{name}%"]} }
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The groups controller will be restful with just a couple of extra instance variables to load up the users. I'm only going to include the creation methods here...&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;class GroupsController &lt; ApplicationController

  def new
    @group = Group.new
    @users = @group.users
    respond_to do |format|
      format.html 
      format.xml  { render :xml =&gt; @group }
    end
  end

  def create
    @group = Group.new(params[:group])
    @users = @group.users
    respond_to do |format|
      if @group.save
        flash[:notice] = 'Group was successfully created.'
        format.html { redirect_to(@group) }
        format.xml  { render :xml =&gt; @group, :status =&gt; :created, :location =&gt; @group }
      else
        format.html { render :action =&gt; "new" }
        format.xml  { render :xml =&gt; @group.errors, :status =&gt; :unprocessable_entity }
      end
    end
  end
  
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the users controller setup a couple of custom actions that will be called via ajax.&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;class UsersController &lt; ApplicationController

  def load_user
    render :partial =&gt; "/users/details", :locals =&gt; {:user =&gt; User.find(params[:id])}
  end

  def autocomplete
    render :json =&gt; User.autocomplete_name(params[:term]).collect{ |user| {:value =&gt; user.id, :label =&gt; "#{user.name}"} }
  end
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;load_user&lt;/code&gt; is called once you have selected the user you want from the autocomplete suggestions. &lt;code&gt;autocomplete&lt;/code&gt; does the searching for users based on the text the user enters. The json returned is digested by the javascript.&lt;/p&gt;

&lt;p&gt;Routes will be as per normal except you'll need to update the users like so...&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;ActionController::Routing::Routes.draw do |map|
  map.resources :users, :collection =&gt; {:load_user =&gt; :get, :autocomplete =&gt; :get}
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now in groups/new .erb file you'll need...&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;&amp;lt;h1&amp;gt;New group&amp;lt;/h1&amp;gt;

&amp;lt;%= error_messages_for :group %&amp;gt;
&amp;lt;% form_for(@group) do |f| %&amp;gt;
  
  &amp;lt;%= f.label :name, &amp;quot;Group name&amp;quot; %&amp;gt;
  &amp;lt;%= f.text_field :name %&amp;gt;

  &amp;lt;div&amp;gt;
    &amp;lt;label for=&amp;quot;user_name&amp;quot;&amp;gt;Add new user&amp;lt;/label&amp;gt;
    &amp;lt;%= text_field_tag &amp;quot;user_name&amp;quot;, nil, :class =&amp;gt; &amp;quot;text&amp;quot;, :id =&amp;gt; &amp;quot;user_name&amp;quot; %&amp;gt;
  &amp;lt;/div&amp;gt;

  &amp;lt;fieldset class=&amp;quot;data_container&amp;quot;&amp;gt;
    &amp;lt;% users.each do |user| %&amp;gt;
      &amp;lt;%= render &amp;quot;/users/details&amp;quot;, :user =&amp;gt; user %&amp;gt;
    &amp;lt;% end %&amp;gt;
  &amp;lt;/fieldset&amp;gt;
  
  &amp;lt;%= submit_tag %&amp;gt;
  
&amp;lt;% end %&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So the gorup has a name attribute and below that is the autocompelte text input for searching for users. Below that we render out all the user details attached to the group, in reality i've split these fields into a partial where they are re-used in the edit action.&lt;/p&gt;

&lt;p&gt;The users/details partial looks like this...&lt;/p&gt;

&lt;pre&gt;&lt;code class="ruby"&gt;&amp;lt;div class=&amp;quot;user_details&amp;quot;&amp;gt;
  &amp;lt;h2&amp;gt;&amp;lt;%= user.name %&amp;gt;&amp;lt;/h2&amp;gt;
  &amp;lt;dl&amp;gt;
    &amp;lt;dt&amp;gt;Address&amp;lt;/dt&amp;gt;
    &amp;lt;dd&amp;gt;&amp;lt;%= user.address %&amp;gt;&amp;lt;/dd&amp;gt;
    &amp;lt;dt&amp;gt;Telephone&amp;lt;/dt&amp;gt;
    &amp;lt;dd&amp;gt;&amp;lt;%= user.telephone %&amp;gt;&amp;lt;/dd&amp;gt;
  &amp;lt;/dl&amp;gt;
  &amp;lt;%= hidden_field_tag &amp;quot;group[user_ids][]&amp;quot;, user.id %&amp;gt;
  &amp;lt;%= content_tag(:p, link_to(&amp;quot;Remove user&amp;quot;, &amp;quot;#&amp;quot;, :class =&amp;gt; &amp;quot;remove_user&amp;quot;)) %&amp;gt;
&amp;lt;/div&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This partial is rendered whenever you select a user. The user attributes you output are not important, the key is the hidden field containing the user id. By passing this through in the form rails will automagically create all the &lt;code&gt;group_member&lt;/code&gt; join records required to link the users to the group. No additional controller code is required.&lt;/p&gt;

&lt;p&gt;In your javascript file add the following. Note that you will need jQuery UI 1.8&lt;/p&gt;

&lt;pre&gt;&lt;code class="javascript"&gt;$(function() {
  $("#new_group, #edit_group").autocompleteUserName();  
});

$.fn.autocompleteUserName = function(){
  return this.each(function(){
    var input = $("#user_name", this);
    var dataContainer = $('.data_container',this);
    
    var loadData = function(item){
      if(item){
        var user_id = item.value;
        $.get("/users/load_user", {id:user_id}, function(data){
          if(data){ dataContainer.html(data); }
        });
      }
    }
    
    input.initAutocomplete(loadData, "/users/autocomplete");
    
    // remove links
    dataContainer.delegate('.remove_user','click',function(){
      $(this).closest('.user_details').remove();
      return false;
    });
  });
};


$.fn.initAutocomplete = function(callback, source){
  return this.each(function(){
    var input = $(this);
    input.autocomplete({
      source: source,
      minLength: 2, //user must type at least 2 characters
      select: function(event, ui) {
        if(ui.item){ 
          input.val(ui.item.label); 
          callback(ui.item);
        }
        return false;
      },
      focus: function(event, ui) { // triggered by keyboard selection
        if(ui.item){ input.val(ui.item.label); }
        return false;
      },
      change: function(event, ui) { // called after the menu closes
        if(callback){ input.val(""); }
      } 
    });
  });
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So the &lt;code&gt;autocompleteUserName&lt;/code&gt; function takes the user search string, sets up an ajax callback called &lt;code&gt;loadData&lt;/code&gt; that will load the html onto the page and then calls the &lt;code&gt;initAutocomplete&lt;/code&gt; function. This function uses the &lt;a href="http://docs.jquery.com/UI/Autocomplete"&gt;autocomplete functionality built into jQuery&lt;/a&gt;. Take a look at the jquery api to see how the autocomplete box behaviour can be tweaked.&lt;/p&gt;

&lt;p&gt;I've split &lt;code&gt;initAutocomplete&lt;/code&gt; out into its' own function so that I can have multiple autocomplete boxes that load different data.&lt;/p&gt;

&lt;p&gt;I've also included a small amount of code in the &lt;code&gt;autocompleteUserName&lt;/code&gt; function to allow for the removal of users from the group.&lt;/p&gt;

&lt;p&gt;Below are some CSS styles are taken from the jQuery api and tweaked so they should provide a decent starting point...&lt;/p&gt;

&lt;pre&gt;&lt;code class="css"&gt;.ui-autocomplete { position: absolute; cursor: default; }	
* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */
.ui-menu {
	list-style:none;
	padding: 0px;
	margin: 0;
	display:block;
	float: left;
	border:1px solid #494849;
}
.ui-menu .ui-menu-item {
	margin:0;
	padding: 0;
	zoom: 1;
	float: left;
	clear: left;
	width: 100%;
	text-align:left;
}
.ui-menu .ui-menu-item a {
	text-decoration:none;
	display:block;
	line-height:1.4;
	zoom:1;
	background:#FFF;
  padding:5px;
}
.ui-menu .ui-menu-item a.ui-state-hover,
.ui-menu .ui-menu-item a.ui-state-active {
	font-weight: normal;
	background:#717171;
  color:#FFF;
  text-decoration:none;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hope this helps someone out there!&lt;/p&gt;</description>
      <guid>http://www.paulsturgess.co.uk/articles/show/95-autocomplete-text-input-using-unobtrusive-jquery-in-ruby-on-rails?action=show&amp;controller=articles</guid>
    </item>
  </channel>
</rss>
