Show SVN revision number in a Rails application

This is a hack to display the Subversion revision in a Rails application using Capistrano to insert the current revision number on each deploy.

Create a partial that will contain the revision number. For example, ~/app/views/layouts/_revision.html.erb. You can put anything in that file, as it will be overwritten by Capistrano on each deploy. The word “Development” or “Current” seems a good choice.

In the page where you want to display the revision number (probably in the application layout), render the partial. In development mode, you’ll see something like “version 1.0.Development”. In your deployment environment, you’ll see the SVN revision number, like so: “version 1.0.504”.

version 1.0.<%=render :partial => 'layouts/revision'%>

To set up Capistrano, edit the ~/config/deploy.rb file (assuming you are already using Capistrano for deployments). Add a task to get the SVN version and write that to your revision partial. For some reason, pointing to the “/current” directory doesn’t work – probably because of the way Capistrano links directories. Therefore, just point SVN to any subdirectory or file to get the version.

desc "Write current revision to app/layouts/_revision.rhtml"
task :publish_revision do
  run "svnversion #{deploy_to}/current/app > #{deploy_to}/current/app/views/layouts/_revision.html.erb"
end

And tell Capistrano to run this task just before restarting the application:

before 'deploy:restart', 'publish_revision'

FizzBuzz one-liner in C#

FizzBuzz: Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. Reference

Console.WriteLine(String.Join(Environment.NewLine, Enumerable.Range(1, 100)
    .Select(i => (i % 3 == 0) ? new { n = i, w = "Fizz" } : new { n = i, w = "" })
    .Select(o => (o.n % 5 == 0) ? new { n = o.n, w = o.w + "Buzz" } : o)
    .Select(o => o.w == "" ? o.n.ToString() : o.w)));

jQuery Autocomplete and Rails

This is an example of how I used the jQuery Automcomplete Widget with Rails 3.2 for a recipe search field. Some of the jQuery stuff mentioned below is included out of the box with a new Rails application.

  • Make sure the jQuery gem is referenced in the Gemfile
gem 'jquery-rails'
  • Include the jQuery javascripts in app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require jquery-ui
  • Download one of the jQuery-ui css files, or a custom one, and put it in one of you asset locations. I put mine in vendor/assets/stylesheets/jquery-ui-1.8.18.custom.css. Include the css file in app/assets/stylesheets/application.css
*= require jquery-ui-1.8.18.custom.css
  • Create a controller action to search and return values for the autocomplete dropdown menu. In my Recipes controller (you could also create a seperate Search controller), I created an Action to return a list of matching recipe titles as a json array. The search can also be applied to recipes in a single category, hence the category_id parameter.
  def search_on_title
    # search_on_title is a method on the model to do a wildcard search on keyword
    recipes = Recipe.search_on_title(params[:term], params[:category_id])
    render json: recipes.map(&:title)
  end
  • Add a route for the search_on_title action.
  resources :recipes do
    get 'search_on_title', :on => :collection
  end
  • The search form is just a normal form.
  <%= form_tag '', :method => :get do %>
	<%= search_field_tag :term, params[:term], :class=> "input-large" %>
	<%= submit_tag "Filter", :name => nil, :class => 'button btn', :id => "search_bn" %>
  <% end %>
  • The javascript to hook up the autocomplete functionality looks like this. Notice the extra parameter to the source url – that’s how you would pass multiple values to your filter.
$("input#term").autocomplete({
    source: '<%=search_on_title_recipes_path%>?category_id=<%=params[:category_id]%>',
    minLength: 2, delay: 500
});

There’s also a Rails gem to make autocomplete easier, but I found this to be easy enough such that I didn’t have to depend on an additional plugin.

WCF Client and the “using” Statement

As I was researching patterns and practices for a WCF client implementation, I came across a bug in the .Net implementation of ClientBase<T> (whether it’s actually a bug is arguable). It’s well documented on the web, but it could cause major headaches if you happened to miss it.

The core of the issue is that ClientBase<T> implements IDisposable. With this knowledge, just about any programmer would naturally wrap its usage in a using{} block. Digging deeper, you’ll find that the ClientBase<T> Dispose() method simply calls Close() on the underlying connection. This is problematic because in certain connection states (such as “Faulted”), the Close() will fail. As I said, this is well documented elsewhere, for example: on MSDN, Stack Overflow, and here.

There are a few different solutions to this issue. I went with a simple Disposable wrapper…

// Get a disposable MyClientWrapper object
using(var clientWrapper = ClientFactory.GetMyClientWrapper())
{
    clientWrapper.Client.DoSomething();
}
 
public class MyClientWrapper : IDisposable
{
    private readonly MyClient _client;
 
    public MyClientWrapper(Binding binding, Uri endpoint)
    {
        // creates an instance of MyClient, which is derived from ClientBase<T>
        _client = new MyClient(binding, new EndpointAddress(endpoint.ToString()));
    }
 
    public MyClient Client
    {
        get { return _client; }
    }
 
    public void Dispose()
    {
        // safe dispose with extension method (below)
        _client.CloseProxy();
    }
}
 
// extension method for safe Close() on ClientBase<T>
public static void CloseProxy(this ClientBase<T> proxy) where T : class
{
    try
    {
        if (proxy.State != CommunicationState.Closed 
                && proxy.State != CommunicationState.Faulted)
        {
            proxy.Close(); // may throw exception while closing
        }
        else
        {
            proxy.Abort();
        }
    }
    catch (CommunicationException)
    {
        proxy.Abort();
        throw;
    }
}

Find/Kill a Linux Process by Name

I was doing some research to figure out how to easily kill a Linux process given part of it’s name. It’s fairly simple to do it manually, but if you didn’t already know, programmers are lazy.

The first thing I was doing…
> ps aux | grep Foo
find the process ID (PID) with my eyes, and then kill it…
> kill -9 123456

Next, I started finding complex piped commands to find and extract the PID. For instance…
> pid=`ps -eo pid,args | grep Foo | grep -v grep | cut -c1-6`

and slightly simpler…
> ps aux | grep Foo | grep -v grep | awk ‘{print $2}’

Finally, I discovered pgrep and pkill. There are quite a few options for each command, but simply put:

To get the PID for a process with a name containing ‘Foo’…
> pgrep Foo

To get the PID for a process with a command line containing ‘Bar’ (as in > Foo -n Bar)…
> pgrep -f Bar

Slow Gardening



Bellpepper

Originally uploaded by cleverswine


This summer is getting off to a slow start, as are our vegetables. We planted tomatoes, cucumbers, zucchini, various peppers, and carrots. So far we haven’t picked a thing. We’ve barely reached the 80s in temperature, and we’ve had more rain than usual. However, despite the lack of veggies, I’m personally enjoying the cool summer.

Simple Moq

I recently worked on a project in which 90% of its tests were integration tests because the core purpose of the project was to interact with external entities. In an effort create more unit tests, I employed Moq (and lots of refactoring).  This is an example of basic Moq usage.

Let’s say we have a repository that gets documents from a database.  The assumption is that a repository interface, IDocumentRepository, is being implemented.

In my case, I found it easier to deserialize results from file, rather than building the results by hand for each mocked response.  I used System.Xml.Serialization to serialize real responses to file.

Let’s Moq it…

var mockRepository = new Mock<IDocumentRepository>();
 
// if the query is for text/plain documents only, mock a response for that
mockRepository.Setup(p => p.FindDocuments(
	It.Is<DocumentQueryParams>(q => q.MimeType == "text/plain")))
	.Returns(DeSerializeResults<List<Document>>("TextDocuments.xml"));
 
// use It.IsAny to return the same result regardless of the parameters
mockRepository.Setup(p => p.FindDocuments(
	It.IsAny<DocumentQueryParams>()))
	.Returns(DeSerializeResults<List<Document>>("AllDocuments.xml"));

My Favorite Albums (Right Now)

This is what I’m listening to…

The Record by FEAR

This is old school punk from the early 80s, when punk rock was a means of expression and rebellion.  This particular album is humorous and offensive, as punk should be.

Gothic Kabbalah by Therion

This isn’t my favorite Therion album, but I’ve been listening to it a lot lately because of some catchy songs.  I find it good to write code to because it takes you to another world.

Soviet Kitsch by Regina Spektor

This is something that’s generally outside of my musical tastes, but I like her quirky voice and odd lyrics.  She reminds me of a disturbed version of Tori Amos.

The Other Side of Time by Mary Fahl

I once claimed that Tarja has the greatest female voice, but I actually meant Mary Fahl.  This album is completely not my style of music (folk/new age/soft rock), but her voice is irresistible and addictive.

Mary Fahl