Text

Macports puts its libraries in non-standard locations, so to build the mysql2 gem on an OSX computer, you will need to do a little bit of extra work to ensure that gem calls make with appropriate options.

To cut a short story, very short, you do this (at least if you have macports in /opt/local (the default), and are using the mysql55 package).

$ gem install mysql2 -- --with-mysql-lib=/opt/local/lib/mysql55/mysql --with-mysql-include=/opt/local/include/mysql55/mysql 
  
Text

TL;DR Basically it is all Google's fault.

We've seen some pretty epic PHP rants this year, probably the most famous among them are PHP a Fractal of Bad Design, and Jeff Atwood's latest (in what seems to be a biennial broadside) The PHP Singularity.

The common thread in these rants is incredulity that anyone would, in 2012, write new code in PHP. There's a lot of reasons why someone might write greenfield PHP code in 2012. But equally (and this is said as a decade long PHP programmer) I have to admit that plenty of the criticisms levelled at PHP are valid. Yet, for the most part they just don't, particularly, matter.

One criticism that is wholly invalid yet comes up time and time again, is that using PHP intrinsically leads to bad code. I don't feel this is an inherent trait of PHP itself, so much symptomatic of the popularity and low barrier to entry of PHP. Basically there's more examples of bad code out there compared to pretty much any other platform because there's simply more code out there, written by programmers of wildly varying skill. The other problem, is that PHP came into existence as a scratch to a C programmer's itch. PHP was developed at a time where people still actually wrote web applications in C and where the stateless nature of HTTP was relatively respected. PHP, like the web itself, has moved on dramatically since then.

A modern PHP 5.4 webapp looks about as similar to an early 00s PHP 4 webapp as Scala does to Java. Yet many critics when slating the language appear to be code archeologists, excavating pre-historic practices that went out of favour long-ago.

This can be partially forgiven, because owing to the age of the language there's plenty of out of date information out there with high rankings in Google. The ubiquitous w3schools is an unfortunate example of bad practices coming well ahead of sites with more modern approaches to solving problems in PHP.

So 'New PHP' is very different to 'Old PHP'. But the 'Old PHP' is what most people seem to find when searching in Google and this confuses people.

We see this manifested in blogs like Will Rails become the new PHP. This blog has a number of spectacular shortcomings, most egregiously the author's horribly naive view of the PHP community, but the interesting one is his ignorance of the power of Google.

There's plenty of support out there for budding PHP programmers, whether on the web, on forums, or IRC. There are countless, well attended, supported and growing conferences, meetups and the like for PHP programmers. One thing that a community cannot do, is force Google to nuke w3schools' PageRank. Which means that brilliant efforts like PHP The Right Way get swamped by old, incorrect and at times dangerous dreck.

And what the 'Will Rails become the new PHP' author perhaps hasn't realised, is Rails, at least in the terms he's trying to couch it, has already become the 'New PHP'. I am a novice Rails developer, I like to hack around in it as it can be quite fun to spike out solutions. What I've been struck by, is the sheer amount of bad advice out there. Advice novices will come across, if they turn to Google for help.

If you're well versed in a platform you learn through brutal experience what works, what doesn't and your nose is finely tuned to bullshit. When I read a PHP article I know instinctively if what I am reading is reliable. But with Rails, as a novice, I don't quite have that sense, beyond my own background experience with other programming languages.

So let's look at an example. I've been working on a dead simple Rails authentication webservice. It listens for HTTP requests for /login, /logout, /session, etc., and emits either XML or JSON in response. I'm using the respond_to method to serve out these responses. Unfortunately what I found is if I request a route that does not exist, I get an HTML error back. This doesn't make a lot of sense for a webservice that otherwise speaks XML and JSON.

Other global exceptions similarly respond with HTML. I don't want to wrap every action up in a begin/rescue block and there is certainly no way to intercept router exceptions in actions anyway. So I needed to learn how to catch global exceptions.

In my journey of (Google) discovery I came across this blog post and appeared to hit paydirt. The advice appears to be legit, hell someone in the rails community even featured it in a podcast. So on the face of it this seems good. But that switch statement sure is smelly. Does it, really, need to be this hard?

Now my general purpose programming brain recognised that this code while solving my problem, is not ideal. And why is it not ideal? This one method sure has a lot of responsibility. Method names with plurals in them are usually a code smell. Over time as more specific exceptions need to be handled I would end up with code that is as easy to read as Goethe's Faust, photocopied and in the original Gothic script (not easy). What we have here is a God Method in training.

Now, what if I am a Ruby/Rails/Programming novice? I have got plenty of other stuff to learn, I'm going to go right here and Cargo Cult this code into my webapp and move on. Just like all the rookie PHP coders do, right?

Well, I didn't do that. I saw that this rescue_from method was pretty awesome and so I went to the Rails API docs to look it up.

API docs for any language are pretty terse, but what jumped out at me was this line:

“Handlers are inherited. They are searched from right to left, from bottom to top, and up the hierarchy. The handler of the first class for which exception.is_a?(klass) holds true is the one invoked, if any.”
  

This isn't great documentation admittedly, but it means basically, if you put rescue_from Exception at the bottom of the list of rescue_from handlers in your application_controller.rb file, then since everything derives from Exception, nothing else will get a look in (Rails will look at the handlers from the bottom up).The author of that helpful blog we found didn't realise this, and so his solution was needlessly complicated.

What can we learn from this? Well Rails programmers certainly live in a glass house and shouldn't throw stones is one thing. But on a slightly less trollish note, there is a problem here for all novice programmers that turn to Google to help them solve problems. The answers on Google are usually either wrong, or at best, incomplete. As the web gets older, bad and out of date advice piles up making it much harder for novices to find good advice.

Knocking a language for this phenomenon (or a framework, seriously, whatever) is more than a little ignorant and doesn't solve the problem. Efforts like PHP The Right Way is how PHP is trying to fix it. If Rails really doesn't want to be the 'Old PHP', they need to realise it's less to do with languages and platforms, and more about SEO.

Text

I wanted to see which images I had in a directory that were a certain set resolution and decided to see how easy it was to do in ruby.

Turns out with a little

gem install image_size
  

It's pretty easy!

Tags: ruby snippet
Text

In PHP it's very common to use a variable as an associative array key:

$keys = array('mykey', 'another_key');
  $array = array();
  foreach ($keys AS $key) { $array[$key] = "hello world\n"; }
  foreach ($keys AS $key) { echo $array[$key]; }
  
  >> hello world
  hello world
  

In Ruby, the presence (and use of Symbols) makes this a bit tricky:

keys = ['mykey', 'another_key']
  myarray = { :mykey => 'hello world', 'another_key' => 'goodbye world' }
  myarray.each { |k| 
    puts myarray[k]
  }
  
  >> hello world
  goodbye world
  

Now if we try this again using instead the Strings from the keys array we get a different result:

keys.each { |k| 
    puts myarray[k]
  }
  
  >>
  goodbye world
  

We don't get the first array value back because a String key is not the same as a Symbol key, even if they consist of the same sequence of characters. This is one of the gotchyas with Ruby.

In Ruby the 'value of a Symbol is not the same as that of a String. So :key != "key". From an ease of use perspective it would be convenient if they did.

Thankfully the language stewards saw fit to include String.to_sym as a convenience method to create a Symbol from a String's value.

keys.each { |k| 
    puts myarray[k.to_sym]
  }
  
  >> hello world
  
Tags: ruby
Text

In these formative stages of my experience with Ruby, one feature of the language that I keep feeling on uneven ground with are Symbols.

I had a feeling I should give them respect as much of the learning Ruby literature says to basically ignore them for now, or launch into lengthy defences of why they exist (usually forgetting to explain how they work).

In case you're unfamiliar with Ruby syntax, a Symbol looks like this

:a_symbol
  

With the numerous ways of defining variables in Ruby this is another variable looking constuct, except that it isn't actually a variable at all (you cannot assign to it).

So what is a Symbol, actually. To be honest I'm still struggling for a good simple definition. I think the best way to think of it, is as a constant (i.e. immutable) placeholder for the name of something. Or more practically put, a colon in front of the string you want to use for a hashkey. Agile Programming With Rails 4th Ed puts it simply 'a Symbol is a name for something'.

I wrote on Twitter that I felt Symbols were extra syntax put in to solve a problem a programmer in a high level interpreted language shouldn't have to worry about. Memory management. In Ruby everything is an object, and objects are much bigger than the primitives you have in Java, C or even PHP. A string for example in PHP (and as in C) is still ultimately a sequence of bytes stored in contiguous memory addresses. In Ruby, a string is always an object, and that requires a fair chunk of memory to represent. If you have a bunch of hash tables, using objects as a hashkey is inefficient and wasteful.

Symbols help solve this inefficiency. A Symbol is still an object, but a special one. It has few methods the main ones being to get its string value and another its integer value, it's immutable and there's only ever one copy of it. So it's much more efficient to use a symbol as a hashkey than a Ruby string. In Ruby (and most OO languges) two strings even if consisting of the same sequence of characters are different objects. In Ruby two symbols of the same sequence of characters are the same object. In large applications this feature can save a tremendous amout of memory.

The other key characteristic of Symbols is immutability. Symbols cannot be assigned to, they just are. In a language that lacks a true constant construct (uppercasing a variable name is the convention for defining a Ruby constant but read-only access isn't enforced at runtime, you can write to what Ruby calls a 'constant'), Symbols can be useful.

So are Symbols a good language feature? At this point with my lack of experience with Ruby I don't really feel qualified to answer that yet definitively. My gut though, says no. I feel in a high level language the need for extra syntax to optimise code adds an unnecessary burden on the programmer. They seem so out of place in a language that works so hard to strip away unneccessary syntax. Symbols, to me detract from Ruby's power to define elegant and natural sounding expressions.

The difficulty authors have in describing what Symbols are, how to use them and why they should be used seems like a language design smell to me. I dare say as I become more familiar and accustomed to the presence and use of Symbols I'll learn to accept them. But as a Developer new to Ruby, they seem out of place.

I haven't gone into an excessive amount of detail about the nature and application of Symbols. For that the two best resources I've found explaining are http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols and http://www.troubleshooters.com/codecorn/ruby/symbols.htm.

Tags: ruby
Text

If you're running OSX Snow Leopard and Macports MySQL, you might run into some drama trying to get Ruby and Mysql playing nicely together.

This can manifest itself in a number of ways, but the most common, I think, is what happened with me

aaron ~/Development/ruby/testapp $ rake db:create (in /Users/aaron/Development/ruby/testapp) Couldn't create database for {"reconnect"=>false, "encoding"=>"utf8", "username"=>"dbuser", "adapter"=>"mysql", "database"=>"testapp_development", "host"=>"127.0.0.1", "pool"=>5, "password"=>"testpwd"}, charset: utf8, collation: utf8_unicode_ci (if you set the charset manually, make sure you have a matching collation)

Seems the mysql driver gets confused a little bit as when you install the MySQL Rubygem as directed by Rake, you link against the bundled OSX MySQL and not the Macports one.

The solution is to install the mysql gem as follows (uninstalling it first, if necessary)

sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- --with-mysql-config=/opt/local/bin/mysql_config5

Substitute the mysql_config5 path with your own macports mysql_config path. Afterwards, everything should work fine.

aaron ~/Development/ruby/testapp $ rake db:create (in /Users/aaron/Development/ruby/testapp)

Text

Now after the hype surrounding the language has died down somewhat, I'm getting acquainted with Ruby and learning the ropes.

To guide me through the Ruby syntactic jungle is O'Reilly's 'Learning Ruby' book. I checked out the ubiquitous Pragmatic Programmer's 'Programming Ruby', but the third edition seems more suited to stopping doors than teaching Ruby.

Reading through the first few chapters of 'Learning Ruby' has left me a little nostalgic of the early 90s when I was going through my first programming book 'Learning Perl'. Maybe it's the title similarities but mostly it's that Ruby's syntax feels as slippery to me as Perl's did.

I don't mean that in an endearing way.

While I'm in love with blocks (or closures whatever you prefer) and Procs and Mixins (Traits), a simple thing scares me. Constants.

Constant, the word is pretty clear in its meaning. It is a value which remains stable over time. Wikipedia says: 'a constant is a special kind of variable whose value cannot typically be altered by the program during its execution'. Collins dictionary says: ‘something that does not or cannot change or vary’.

Ruby though, says no. Constants are just global variables declared capitalised. Oh sorry that should be capitalized. Ruby doesn’t speak English, only American. A constant in Ruby is about as constant as your discipline. If you REALLY want to change its value, Ruby wont stand in your way, or even make it that hard to do.

That really, really concerns me. Part of the appeal of Ruby, I guess, is that it lets you do things you want, your way. Maybe it’s ‘Fear’ but I really don’t want to have to worry about my constants changing. Ruby makes a big deal of its ‘duck typing’ You know, if it quacks like a duck, it is a duck. Unfortunately in Ruby a constant quacks like a duck but it bites like a hippo.

Tags: ruby