Using Datamapper with Rails 4

Was trying to swap out active record for datamapper on a rails 4 application this morning and had one or two issues with gem version conflicts (I think this is largely due to DM being discontinued in favour of the not-done-yet ROM). At time of writing if you install with rails 4.0.0 and just go for the rubygems repo you’re going to get moaned at for having incompatible gems.

For a fresh rails 4 application you can get around this by installing from github and specifying “release-1.2” as the branch. I managed to get the full suite up and running by adding the following to my Gemfile (adapted from this guide).

%w{core constraints migrations transactions timestamps do-adapter rails active_model sqlite-adapter}.each do |gem|
  gem "dm-#{gem}", :git => "{gem}.git", :branch => 'release-1.2'

What does it do? Basically, it iterates through a bunch of strings interpolating those strings into a gem name and git repo name, and for each one, specifies branch “release 1.2” and gets the gem for that. Whoever maintains those repos has certainly been consistent!


Migrating a rails postgres based application to MySql

Had an application which started out on nginx/postgres, but needed to migrate it to apache/mysql (short summary of reason is that we had some php/mysql-compatible only apps and we didnt’ want to be running two servers). Anyway, here’s how we achieved it.

First get to the point where the application deploys to the new server. If you have your cap recipes set up like I do, that’ll mean you get the structure/indexes and so on all set up and you’ll basically have an “empty” application, save for your master data.

Once it’s there and running, we’re just going to need to do a data-dump of the postgres database, which you can do from your pg server with the following command;

pg_dump replace_with_database_name -f replace_with_database_name.sql --data-only --no-owner --no-acl --attribute-inserts --disable-dollar-quoting --no-tablespaces

Obviously replacing the bit about “replace_your_database_name” with your actual database name. What you’ll end up with is a file with *just* the commands required to do the inserts of your master data. There is some stuff you need to delete from there too though, specifically;

  • The schema migration records (those will already be in the new application from when you deployed it)
  • Any seeded data (for the same reason)
  • any references to postgres system tables (there shouldn’t be any of these if you dumped with the above)

So basically, once you have that file, you can just import it into your MySql database. I personally use phpMyAdmin, just basically open that and paste the file into the SQL tab, hit go, and there you go!

Escape html fractions in rails

One requirement of a project I’m undertaking at the moment is that the user should be able to enter ingredients into a CMS like this;

1/2 kg sugar

but that when it renders it should convert their 1/2 into the “half” html escape sequence, and similarly for other fractions. There doesn’t appear to be a gem out there that does exactly this, but there was a really nice snippet that provided a good base. With that, it was just a case of using a regex to pull out the fraction characters and a gsub to replace them with an escape sequence. The following therefore went into the application helper file;

#Accepts string and looks for instances of number/number, then attempts to parse those into
#html escape sequences.
def escape_fractions string_with_fractions

   #snippet inspired by
   string_with_fractions.gsub(/\d\/\d/) do |match|
   case match
      when "1/2" then '@amp;frac12;' # One half
      when "1/4" then '@amp;frac14;' # One quarter
      when "3/4" then '@amp;frac34;' # Three quarters
      when "1/3" then '@amp;#x2153;' # One third
      when "2/3" then '@amp;#x2154;' # Two thirds
      when "1/5" then '@amp;#x2155;' # One fifth
      when "2/5" then '@amp;#x2156;' # Two fifths
      when "3/5" then '@amp;#x2157;' # Three fifths
      when "4/5" then '@amp;#x2158;' # Four fifths
      when "1/6" then '@amp;#x2159;' # One sixth
      when "5/6" then '@amp;#x215A;' # Five sixths
      when "1/8" then '@amp;#x215B;' # One eighth
      when "3/8" then '@amp;#x215C;' # Three eighths
      when "5/8" then '@amp;#x215D;' # Five eighths
      when "7/8" then '@amp;#x215E;' # Seven eighths
   else match

NB You’ll need to replace all @ symbols with & – couldn’t for the life of me work out how to stop wordpress escaping them!

Anyway, this allowed the view to do things like this;

<% @recipe.ingredients.each_line do |ingredient_line| %>
<li><%= escape_fractions ingredient_line %></li>
<% end %>

Comma seperated list of links in rails

One very common requirement of web applications is to have a comma-separated list of links display in the browser (usually things like categories or tags). This is traditionally quite annoying for programmers because the usual approach is to iterate through an enumerable object and build up a string, then deal with the messy business of shaving off that inevitable “last comma” so your links don’t end up looking like this;

Games, Movies, Videos,

As always, such things are much easier in ruby. In the case of a rails application, if you place the following code in your application helper file;

  def comma_seperated_links_for(list)

    raise TypeError, "parameter must be an array" unless list.is_a? Array 
    return if list.count == 0

    list.collect do |item| 
      raise TypeError, "items must respond to 'name'" unless last_item.respond_to? :name
      link_to(, url_for(item)) 
     end.join(", ").html_safe

You can lean that up by removing all of the “raise” calls, I only include them here to demonstrate the limitations of the implementation. Not only is this a slick and efficient implementation, it also means you get a huge dose of Knuthian readability straight into your views 🙂

   <%= comma_seperated_links_for @product.categories %>

PDF generation in rails 3 with prawn

Firstly, as always, there is a fantastic Railscast by Ryan Bates which explains Prawn perfectly. Having said that, there are a few things that it doesn’t mention that you need to do in order to use prawn in Rails 3. The path to getting this working is as follows;

#First install prawn on your system (lose the sudo if you're running under RVM)
sudo gem install prawn

#install the prawnto plugin
rails plugin install

#add prawn to your Gemfile
gem "prawn"

After this, you should be able to do everything Ryan does in his railscast 🙂

Creating your own attr_accessor in Ruby

When going through Ruby 101, you won’t need to do much research before you come accross the use of the attr_accessor methods. There are several flavours of this;

attr_accessor gives you a getter and a setter
attr_reader just gives you a getter
attr_writer just gives you a setter

Here’s a code example of this functionality being used;

class Person
  attr_accessor :name, :age

#above class definition enables the following
p = = "Mikey"
p.age = 30

Magic. It’s almost like you’ve somehow managed to add two more methods to the person class without defining them. Well, it turns out that this is exactly what you have done! For anyone who is not used to dynamic programming languages (and I include myself in that list) this can be a really tricky point in the learning curve. This sort of functionality is used all the time in ruby, and not only within the context of attr_accessors – The Rails framework, for example, uses dynamic code to allow you to add very complex functionality to your ActiveRecord classes with a single line of code.

If you are anything like me, then you can’t just take the fact that it works for granted! I needed to know *exactly* how this sort of thing is possible! This post will clear up exactly how this attr_accessor magic works by showing you how to make your own version of the same functionality.

Dynamic code is created using a series of “eval” methods which the ruby language makes available to you. There are several flavours (eval, instance_eval, class_eval, module_eval) – the one we’ll be using here is class_eval, which you basically use to add code to a class. As we will be trying to create a method that will be accesible from all classes, we will need to add our code to the Class class (not a typo!). This is going to get a bit headswimmy, so I’ll just go ahead and show you the code itself then discuss it below.

class Class
  #firstly, the * decoration on the parameter variable
  #indicates that the parameters should come in as an array
  #of whatever was sent
  def mikeys_attr_accessor(*args)

    #We simply iterate through each passed in argument...
    args.each do |arg|
      #Here's the getter
      self.class_eval("def #{arg};@#{arg};end")
      #Here's the setter
      self.class_eval("def #{arg}=(val);@#{arg}=val;end")                      

The above code allows a new class to be defined as follows;

class Person
  mikeys_attr_accessor :name, :age  

Which in turn allows you to write code like this;

person = = "Mikey"
person.age = 30
puts person.age

A lot was going on in the first code example, but the rest of it functions exactly as you would expect attr_accessor to function. The focus here will therefore be on the first bit of code. So it all starts off pretty basically, we are able in ruby to extend any class simply by using the class keyword. We then add the method “mikeys_attr_accessor” to it, using a bit of ruby syntactic sugar to allow this method to receive any number of arguments. It’s worth pointing out that we should really check that these arguments were symbols, but as this is a simple example I’ll skip that part.

Next we iterate through each argument and make two calls to the “class_eval” method. The message we send to this is basically just an interpolated string representing the code we want included in our object. Yes, I did say object – you might raise the question at this point as to why I’m using the word “object” when we are clearly adding a method to a class. You might also question the presence of the word “self” before the “class_eval” call, surely this would mean that we have somehow managed to create an “instance” of a class?!

This was pretty much the point, while learning Ruby, that I lost cabin pressure.

class Person

=> Class

The capital letter at ths start of Person indicates that it is a constant. Person is constant instance of the Class class. As you’ve instantiated the Class class in your Person class, you need to use “self” on the class eval to make sure that the class_eval method is talking to the Person instantiation of the Class class. You may need to read the previous sentence a few times before it sinks in (if you feel your ears starting to bleed, contact your GP immediately).

A better question is that, if this is the case, why is class_eval used instead of instance_eval? the short answer to that is that it has to do with scope and context. If you are interested in learning a bit more about metaprogramming, i found the following question over on stack overflow to be incredibly useful. Lots of great links from the respondants.

“%” notation for ruby literals

Many examples you will come accross in Ruby involve an odd “%” notation when declaring literals. The syntax is basically a % symbol followed by a pair of any type of bracket or other non alphanumeric character, with some contents between the brackets. All five of the following examples;

=> %{Hello World}
=> %<Hello World>
=> %(Hello World)
=> %[Hello World]
=> %?Hello World?

Will evaluate to the string “Hello World”. While any non alphanumeric character can be used (such as the ? above) you gain more readability using brackets because you can see the opening and closing nature of each bracket. There is one other benefit of using brackets which we’ll come on to in a bit.

Why is this useful? Well, the most obvious benefit is when escaping characters within string literals. The following, for example, would fail due to a syntax error because the string is considered closed when the interpreter encounters the second quote mark;

=> puts "Mikey considers inappropriate use of "quotation marks" in sentences to be a crime against hunanity"

In order to get that working, you’d need to escape the quotes, like so;

=> puts "Mikey considers inappropriate use of \"quotation marks\" in sentences to be a crime against hunanity"

The following, however, would work without the need to escape the quotes;

=> puts %{Mikey considers inappropriate use of "quotation marks" in sentences to be a crime against hunanity}

And just to come back to the second benefit of using brackets instead of other symbols, the following example would fail because the ? inside the literal is not escaped;

=> %?Hello?World?      #This fails
=> %?Hello\?World?     #This is fine because the inner ? is escaped

However, when using brackets, as long as the internal brackets balance then ruby will escape them for you;

=> %<Hello < World>        #This will break because the internal brackets arent' balanced
=> %{Hello {there} World}  #This works just fine!

Decorating the %

The % can be decorated with various mneumonics which further assist ruby in evaluating the contents. The tradition with these mneumonics is that they are alphabetic characters, and that when capitalized these pneumonics allow interpolation to occur. For example, the letter q is used for string literals, and Q for string literals that allow interpolation, as seen in this example. If you attempt interpolation without using the correct mneumonic, your interpolation will be escaped;

=> num = 2
=> %q{1+1=#{num}}      #evaluates to "1+1=\#{num}"
=> %Q{1+1=#{num}}      #evaluates to "1+1=2"

The two i find myself using the most are q and w, which identify strings and arrays respectively as follows;

q string
Q interpolated string
w array of strings
W interpolated array of strings

Just to give one final example of that array notation in action, it’ll basically evaluate the contents to an array of strings using whitespace as a seperator like this;

=> %w{This is an array}     #evaluates to ["this", "is", "an", "array"]

I have seen and used this notation extensively in requiring libraries. For example, the following;

require "rubygems"
require "hpricot"
require "rails"

could be re-written more readably like this;

%w{rubygems hpricot rails}.each { |lib| require lib }