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 Applicatr, 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.
Applicatr has been Launched
Just a quick post announcing that I’ve finally managed to launch my new web application: Applicatr. While the name might sound a bit unusual, and the look isn’t all there yet, it’s pretty functional already (we’ve been using it to find the right graphical designer amongst other people).
For those of you that haven’t clicked the link to check it out, the gist is that its a web application that helps you and your team (or company) collaborate more efficiently during the hiring process so that you end up hiring the right person for the job and for the team.
So if you’re someone that will be involved in hiring anytime soon, give it a go, and feel free to send any feedback.
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.
Simple dataset import/export for Rails
I’ve been doing some Ruby on Rails development recently and one thing that’s bugged me a bit is how to deal with test data while you’re developing the application. Not data that is used just for testing, but data that lives in the development database that you use and fiddle around with while developing the site itself. I’ve found that while developing features of the site I need a fairly large and varied set of data to use, and this data takes a while to enter into the site each time I modify the database.
So instead of repeatedly entering this data I wrote some simple Rake tasks that can automate exporting and importing the data from the database. I can’t take all the credit as the idea was inspired/based on/stolen from the Advanced Rails Recipes book.
Exporting works by writing each table to its own CSV file in the db/dataset directory (or subdirectory) in the rails project. The first line of the file is the name of the columns in the database.
desc "Exports the database contents into CSV files."
task :export => :environment do
require "FasterCSV"
require "FileUtils"
path = File.join(DATASET_PATH, (ENV["DATASET"] || "."))
FileUtils.mkdir_p(path)
ActiveRecord::Base.establish_connection
database = ActiveRecord::Base.connection
(database.tables - SKIP_TABLES).each do |table_name|
FasterCSV.open(File.join(path, "#{table_name}.csv"), "w") do |csv|
# Write column names
csv << database.columns(table_name).map(&:name)
# Write rows
database.select_rows("SELECT * FROM %s" % table_name).each { |row| csv << row }
end
end
end
Importing works much the same way by reading all of the CSV files in the db/dataset directory (or subdirectory) and attempting to load the data into the database. However it does check that the table of that name exists first and skips it otherwise.
desc "Imports data from CSV files into the database."
task :import => :environment do
require "FasterCSV"
path = File.join(DATASET_PATH, (ENV["DATASET"] || "."))
ActiveRecord::Base.establish_connection
database = ActiveRecord::Base.connection
tables = (database.tables - SKIP_TABLES)
database.disable_referential_integrity do
Dir.chdir(path) do
Dir.glob("*.csv") do |file_name|
table_name = file_name[/(.+)\.csv/, 1]
next unless tables.include?(table_name)
rows = FasterCSV.read(file_name)
# Construct a list of column headings from the first row
heading_row = rows.shift.map { |heading| database.quote_column_name(heading) }.join(",")
rows.each do |row|
# Need to escape the data correctly so that inserting is successful
row_data = row.map { |item| database.quote(item) }.join(",")
database.execute("INSERT INTO %s(%s) VALUES (%s);" % [table_name, heading_row, row_data])
end
end
end
end
end
These are faily simple tasks and therefore I’m releasing the code to the public domain, grab the file and use it freely.
To make it work just add it to your lib/tasks directory in your Rails project. The tasks can then be invoked with:
rake dataset:export rake dataset:import
You can also specify a specific subdirectory by passing the DATASET option to rake, like:
rake dataset:export DATASET="dev"
Of course I know there are many things missing from this script, such as being able to specify the rails environment to use, but I’ve kept it simple so adding these features is left as an exercise to the reader.