Limiting template parameters to iterators of a certain type (C++11)

This is a snippet of code that I’ve concocted to restricts the type that can be passed to a function to be only an iterator that enumerated values of a specified type. This allows for a more specialised templated function, where the parameters are guaranteed to be iterators over a certain other type.

template <class Iterator, class T>
struct enable_if_iterates_type :
    public std::enable_if<std::is_same<typename std::iterator_traits<Iterator>::value_type, T>::value, T>
{
};

I hope I’ve made the code fairly self explanatory, but to summarise the Iterator template type is the iterator to accept, and T is the type that the iterator should enumerate. It is then used in the function to represent some type, usually the return type, as such:

template <class Iterator>
typename enable_if_iterates_type<Iterator, int>::type Generate(Iterator begin, Iterator end)
{
    int i = 0;
    std::generate(begin, end, [&i]() { return i++; });
    return i;
}

Now this is just a simple example of how it can be used, where it limits the iterators that can be passed in to those that have a value_type of int. The full test program is at the end of the post.

This came about because in my game engine project I’ve created functions for computing a bounding box that contain a set of other bounding boxes. Initially I had it only accept a vector of bounding boxes, but using this snippet the function can now accept any pair of iterators that conform to the STL iterator mechanism and that iterate through a set of bounding boxes.

#include <iterator>
#include <algorithm>
#include <numeric>
#include <type_traits>
#include <vector>
#include <iostream>

template <class Iterator, class T>
struct enable_if_iterates_type : public std::enable_if<std::is_same<typename std::iterator_traits<Iterator>::value_type, T>::value, T>
{
};

template <class Iterator> typename enable_if_iterates_type<Iterator, int>::type Generate(Iterator begin, Iterator end)
{
    int i = 0;
    std::generate(begin, end, [&i]() { return i++; });
    return i;
}

template <class Iterator> typename enable_if_iterates_type<Iterator, int>::type Sum(Iterator first, Iterator last)
{
    return std::accumulate(first, last, 0);
}

int main()
{
    std::vector<int> int_vector(20);

    Generate(std::begin(int_vector), std::end(int_vector));

    std::cout << "Vector: " << Sum(std::begin(int_vector), std::end(int_vector)) << std::endl;
    std::copy(std::begin(int_vector), std::end(int_vector), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;

    return 0;
}

Freezing DateTime in Ruby on Rails Testing

Since I’ve now used this snippet of code in more than one location I thought I’d share it properly with the rest of the world.

What it does it allow you to freeze the time returned by the DateTime class, which is especially helpful when writing Rails tests. It was inspired by the discussion and suggestions on this thread. So here’s the code.

#
# Partial Mock DateTime object to enable fixing the current time
#
class DateTime
  class << self
    #
    # Mocks out the "now" class method
    #
    attr_reader :mock_time

    def mock_time=(new_now)
      @mock_time = new_now
    end

    def now_with_mock_time
      mock_time || now_without_mock_time
    end
    alias_method_chain :now, :mock_time

    #
    # Helper method to freeze and automatically unfreeze time safely
    #
    def freeze_time(&block)
      frozen_time = now_without_mock_time
      begin
        mock_time = frozen_time
        yield
      ensure
        mock_time = nil
      end
      frozen_time
    end
  end
end

The operation of the class is simple, whenever the @mock_time variable is set it will return that time rather than the actual time for all DateTime.now calls. Set @mock_time to nil to disable it.

There is also a helper function freeze_time which will freeze the time during the block to the time when it was called, returning that time at the end. This makes testing some things a breeze, for instance:

# state= saves the date it was set
state_time = DateTime.freeze_time { some_record.state = :foo }
assert_equals :foo, some_record.state
assert_equals state_time, some_record.state_date

Though a word of caution, since this is a monkey-patch, it should only be included/required in the specific test file that it is used, and definitely not in any production code.

Quote of the Day

When my daughter was 4, I asked her what she thought I did for my work. She replied, “Daddy makes coffee!”. – Tony Albrecht

Quote of the Day

I, too, am allergic to work. Unfortunately, the government does not recognise this as a disability, so I had no option but to become a consultant. – TheRaven64

Quote of the Day

Oh, you hate your job? Why didn’t you say so? There’s a support group for that. It’s called EVERYBODY, and they meet at the bar. – Drew Carey.

Deploying Sass in Rails with Capistrano

As part of implementing the design for a web project, I decided to use SASS (but not HAML), with its new SCSS syntax, for generating the CSS. SASS is useful for me for three simple points:

  • Nested selectors, which really cut down the verbosity of the CSS you have to work with,
  • Mixins, which allow for oft-repeated CSS to be componentised and abstracted away, and
  • Variables, which allow you to specify values in a central location that get used in many rules.

But regardless, there are many blogs out there which will better articulate the value of SASS, but this post is written to show you how to deploy SASS to your server using Capistrano and no other additional plugins or gems.

SASS Rake Tasks

The first thing to do is to add some handy rake tasks that manipulate the SASS plugin. The benefit of creating these rake tasks is that you can execute the SASS actions at any time, so useful for testing and development.

So the sass.rake file goes as such:

namespace :sass do

  task :sass_environment => :environment do
    Sass::Plugin.on_updating_stylesheet { |template, css| puts "Building #{css} from #{template}" }
    Sass::Plugin.on_not_updating_stylesheet { |template, css| puts "Skipping #{css}" }
  end

  desc "Forcefully updates the stylesheets generated by SASS."
  task :build => :sass_environment do
    Sass::Plugin.force_update_stylesheets
  end

  desc "Updates the out of date stylesheets generated by SASS."
  task :update => :sass_environment do
    Sass::Plugin.update_stylesheets
  end
end

Now you might notice the sass_environment task, I use this as a handy place to put SASS configuration and customisation items. The two items located there setup callbacks that print a message for each file that has either been processed or skipped, as I’ve found that this is invaluable in debugging problems with the system.

Also what you might notice is that I’ve set up two rules that can be used to build the CSS. I did this so there would be an easy way to do a clean build of the CSS, without having to manually delete the existing CSS files, and then getting into trouble when you deleted one that wasn’t generated by SASS.

Capistrano

Now that you have a bunch of rake tasks (or just one) that build the CSS, this next step because trivially easy. All you need to do is to add in a callback that will run the required rake task, like so:

# Build the SASS Stylesheets
before "deploy:restart" do
  run "cd #{current_path} && rake RAILS_ENV=#{rails_env} sass:build"
end

The one tricky part (well at least the one I had a bit of trouble with) is to make sure that you use the before deploy:restart callback, since it is only at that stage that the current_path is valid and pointing to the correct version on the server. Also just to be safe I’ve used the task that rebuilds all of the CSS in the deployment, since I don’t want any old styles hanging around.

Finale

Now you can easily deploy the Rails application as before, and you’ll have the styles build on the server as part of it. Additionally if you added the SASS logging in the rake file as I had, you will see what files are being generated on the server in the Capistrano output.

And that’s it, deploying a Rails application that uses SASS is really that simple.

Been working

For the past few months I’ve been working on a startup, something very useful that fills in a need that businesses have.

Right now I’m deep into adding the finishing touches on it so that it can be released for consumption. This does not mean that it’s finished by any stretch of the imagination – I have a todo list that’s as long as a piece of string – but it does mean that we’ve crossed enough t’s and dotted a sufficient number of i’s so that other people can use the website.

If all goes well the site proper should be up and live in a few days at the start of February, and I’ll do another post then.

Stay tuned!

Google Search is Old

I have been using the Google search engine for many years now, and have found it to produce good search results, that is until recently. What’s been annoying me now is that I do frequent searches to find information related to fields that change frequently, such as Ruby and Rails, and the results that I get are the oldest ones which are no longer valid or are innacurate.

Generally when I search for a particular problem I am having, the first results that come up have been from a blog that is 2-3 years old, and about a dozen versions out of date. Though it’s not only Google that has this problem, but a lot of the other major search engines. It’s that they give more precedence to how old a particular site is rather than if it’s relevant anymore. This also disproves the adage that there’s no more innovation to be had in search.

For now though what would be really useful would be the ability to sort the search results by date. From newest to oldest, oldest to newest, so that the information for the newest versions would come out on top rather than be buried in the search results. I’d love to see this as an advanced search option, or even one of those Google search box commands.

Deploying StaticMatic with Capistrano

Recently I’ve developed a site using the simple StaticMatic website generator. StaticMatic is a nice and simple static website generator that uses HAML and SASS to describe the site content while also providing an easy way of using templates much like in Rails. However one thing that it does not do is provide an easy way of doing deployment to a server.

Looking over the deployment options I decided to use Capistrano, mainly as a learning experience before trying to use it to deploy proper Ruby on Rails applications. Though I found out that it’s not that difficult to set up. So here goes my story:

Installation

To deploy StaticMatic via Capistrano you need to use the railsless-deploy package which cuts out the Rails specific cruft from Capistrano.

You might need to add http://gems.github.com (I know they don’t do Ruby gems anymore, but it still works for me) and http://gemcutter.org to your gem sources list. To do this use:

gem sources -a <SOURCE>

Then installing the required packages is simple:

gem install capistrano
gem install railsless-deploy

Setup

First you’ll need to Capify the site, so in the StaticMatic site root directory execute:

capify .

Which will create the Capfile and config/deploy.rb files. These now need to be edited to work with railsless-deploy and StaticMatic.

So the Capfile with the appropriate modifications should look something like:

load 'deploy' if respond_to?(:namespace) # cap2 differentiator

require 'rubygems'
require 'railsless-deploy' # Removes railsisms from Capistrano
load 'config/deploy'

Then the config/deploy.rb needs to be worked on. This is where you set up the configuration for how to deploy the site. There are many settings that need to be set, such as the application, the repository, and the roles available (I just set the roles to the same thing). In addition I use git for source control of this site, so some of my settings are:

set :deploy_to, "/var/www/#{application}"
set :deploy_via, :export
set :scm, :git
set :shared_children, []

Using the export deployment method means that there is no .git directory hanging around on the server for people to muck around with. Setting the shared_children variable to an empty array means that no shared directories are present on the site. While this isn’t essential, I use it so that no superfluous directories are created.

In addition to these settings, a couple of small task definitions need to be included in the config/deploy.rb file, namely:

namespace :deploy do
  task :update do
    transaction do
      update_code
      build_code
      symlink
    end
  end

  task :build_code, :except => { :no_release => true } do
    run "staticmatic build #{latest_release}"
  end
end

These tasks are necessary to build the site on the server, with the first task redefining the deployment task so that the code is built at the appropriate stage, and the second task doing the actual building of the site.

Deploying

Once the site has been configured appropriately a few Capistrano commands need to be executed to set up the environment on the server. Firstly the directory structure needs to be set up, so run:

cap deploy:setup

Then we check that everything is configured appropriately by running:

cap deploy:check

And finally we can deploy the first version of the site using:

cap deploy

Assumptions

Now of course this post isn’t a complete how-to of deploying a StaticMatic site onto a server. Things that I have omitted are setting up a deployment user on the remote site, generating a SSH key, configuring Capistrano with that user information, etc. However there are various other guides out there with this information so it shouldn’t be too hard to find.

Books List

I’ve added a page that contains a list of books that I’ve found interesting from both a personal and professional standpoint. More importantly there are links to both Amazon.com (USA) and Amazon.co.uk (UK) in case anyone wants to buy them, of course I get a tiny cut if people do this.