Top level methods in Ruby

How top level methods work in Ruby

There are many quirks in the Ruby language which IMO show funny behaviours. Take the top level methods, for example – that is, methods defined outside of a class or module. There is something weird about them that makes me wonder about the reasons behind certain design choices. In particular, one thing that I find weird is that Ruby top level methods become private instance methods in all objects.

The reason is that main (the name of the top level context) is an instance of Object:

p self.class
=> Object

So for top level methods to be available on main they are defined as private instance methods on Object, as we can also see if we run:

p Object.private_instance_methods.size

def title
"Mr"
end

p Object.private_instance_methods.size

=> 70
=> 71

This in turn means these methods are basically attached to every Ruby object due to inheritance – that’s how Ruby implements global functions. I am not 100% sure of the reasons behind this behaviour (I might have an idea, read on), but it really looks weird to me. For example, say that we have a top level method called title:

def title
"Mr" # just an example
end

That method will become a private instance method on Object:

Object.private_instance_methods(false).include? :title
=> true

Having a class Person:

class Person
# ...
end

We cannot then call title on any instance of Person because despite the method is available due to inheritance, it is private:

Person.new.title
=> :in `<main>': private method `title' called for #<Person:0x007fba5abbad70> (NoMethodError)

Unless, of course… we use send:

p Person.new.send :title
=> "Mr"

And, because classes are also objects in Ruby, top level methods also become class methods on all classes…

p Person.send :title
=> "Mr"

D’oh.

This may seem innocuous, but it results in ‘polluting’ all Ruby objects, and it certainly happens often. For example, take Cucumber step definitions. I have seen often methods defined directly in the files containing step definitions without being encapsulated into modules or classes; so those methods are basically top level methods, and as such they are attached to all Ruby objects. In the case of Cucumber, it’s easy to avoid this by creating modules and including them at runtime with World(ModuleName). But the problem is, when you add top level methods to a step definitions file -in the Cucumber example- you don’t necessarily intend to be able to call those methods from anywhere.

So.. why aren’t top level methods simply defined as singleton methods on main, instead of being instance methods on Object? Methods defined as top level methods should ideally result in a NoMethodError when called from any other class, but that’s not the case.

One possible reason behind this design choice is that this way you can avoid referring to the main object when calling methods like puts or require, for example. So we can just say puts and require from everywhere instead of something like Main.puts, Main.require. But wouldn’t it be better to explicitly call a method on main rather than polluting all the other objects just for this?

If my assumption is right – that this design choice is explained by the convenience of calling methods like puts and require without having to refer to main – is this behaviour a feature? (Open question for the readers).

It is also interesting that when you try the same code in IRB instead -at least with Ruby 1.9.3- the behaviour is different, and top level methods become instead public instance methods in all objects. So, if you run, in IRB, you’ll see that the behaviour is the opposite of that shown when running the code with the Ruby interpreter:

irb(main):001:0> def title
irb(main):002:1> "Mr"
irb(main):003:1> end
=> nil
irb(main):004:0> Object.private_instance_methods(false).include? :title
=> false
irb(main):005:0> Object.public_instance_methods(false).include? :title
=> true

Does anyone know the reason for this?

Microsoft buys a chunk of Nokia. Surprise!

We saw this coming, didn’t we? It was all planned, and well orchestrated; it’s been a good strategy: send someone to the other company, help it sink, then buy it at a discount price. It was all a con. I love conspiracies. The “mole” ex-Microsoft Stephen Elop was supposed to save Nokia (read his memo on Nokia being a ‘burning platform’) but he is saving Microsoft instead. He has demolished Nokia by first making it undervalued and then giving away to Microsoft its devices and services business on the cheap, for just $7 billion ..Is it just me or does this sound like a bargain? Is that significant portion of Nokia’s business really worth only $7 billion? Wow. I would have guessed/expected much more. Of course Elop will soon be back at Microsoft and will likely follow Steve Ballmer as CEO.

Many say that this may anyway be a good move given that both companies are struggling and out of options, but will two struggling companies make a good one?

By buying the devices and services part of Nokia’s business and acquiring a long term license for its patents, Microsoft will likely try to position itself as a direct competitor for Apple and Google, since it will be able to engineer both software and hardware for its new mobile devices. But I wonder what we should expect in the near future, since neither Microsoft nor Nokia have amazed me with their products or services in the past several years. Will we see a new Kin? 😀

I also wonder what will happen to the other partners that Microsoft currently has and that use the Windows Phone OS on their devices; will they be willing to compete with Microsoft directly or will they jump ship and join the other manufacturers that use Android instead on their devices? Some may argue that this didn’t happen when Google acquired Motorola for $12.5 billion last year, but it’s still possible.

It’s a shame, really, that a company that once upon a time ruled the world of mobile, is kinda slowly dying. My first phone was a Nokia, and so many of the phones I have owned before my first iPhone. It saddens me to think that we will never see another Nokia smartphone 😦

At least there still is Angry Birds! 😀

Why I switched from Jekyll back to WordPress

Back in 2011 I wrote a couple of posts -which became very popular- on why I had migrated from WordPress to Jekyll and on how to perform such migration in great detail. I had become a big fan of Jekyll, so it may surprise that this site is now running on WordPress again after more than two years. At the time, I justified the choice by saying, among other things, that while I thought WordPress was (is) a great CMS, I also thought it was overkill for my needs, due to features I thought I didn’t need. I even blamed WordPress because I wasn’t writing new content as often as I would like, which was unfair.

When I came across Jekyll I was sold on the idea that it was written in Ruby, rather than PHP (which, btw, I absolutely hate) and I could write my posts in Markdown with VIM, yay! Still today, its popularity is growing, also thanks to free hosting with Github Pages.

At first I had fun with the migration, it wasn’t trivial for some aspects but it wasn’t too complex either since I am a Ruby dev. I had to write scripts to import content from WordPress, reproduce the widgets I had with the WordPress version, figure out how to handle syntax highlighting for my code snippets, figure out how to get related posts working, write tasks to optimise static content, and more. However, I enjoyed the results, in particular the speed of the static site generated by Jekyll, achieved without having to fiddle with some caching plugins as I had to do with WordPress. Another thing I really like of Jekyll is that a site generated with it is inherently secure from an application point of view, due to its static nature: there is no dynamic code and no databases, meaning that there are no administration areas to hack into, no plugins or themes with vulnerabilities to exploit, and so on. Plus, a static site combined with a well-tuned web server like Nginx can help mitigate small DoS attacks -well, in some conditions at least.

Blogging with Jekyll seemed OK a first, but after a while I felt like switching from WordPress had been a mistake. For starters, like many others I had been comparing Jekyll to WordPress while in fact these are two very different things, with the former being a static site generator and the latter being a full content management system. I was clearly comparing apples with oranges.

Reasons why I switched back to WordPress

Publishing workflow and build times

The very first thing annoyed me when using Jekyll was the process with which you get new content ‘published’. I’d write my post in Markdown and then rebuild the site so to see the changes; problem is, if while you are writing a post you want to save the draft and quickly preview the post, you can’t. You need to rebuild the site again. This slow process started to be very annoying even though I don’t have many posts yet on this site – I can’t imagine how long it would take to rebuild a site with a lot more content!

Writing new content

The second downside with running a site generated by Jekyll is that I’d be forced to write new content from home or anyway from a computer with both a copy of the code and the ‘tools’ required to rebuild and publish the updated site. With WordPress, I can write new content from anywhere. It’s nice to be able to fire up a browser in a cafe, or wherever, and edit new content when you have some good ideas.

I have also changed my mind about the editor; at the time, for some reason I didn’t like much to write posts with WordPress’ built in editor; but with Jekyll, I eventually got tired of how I had to manually manage images, copy metadata from an existing post to a new post, then change that metadata, write the post, rebuild the site. It was a lot of work, really. With WordPress, the editing experience is so easy and I actually like the editor now while I am writing this post. And you can even use some apps to write content if you are not happy with the built in editor.

SEO

Another thing that with Jekyll you need to take care of entirely on your own is search engine optimisation, while WordPress and many themes available for it are well designed from a SEO point of view already out of the box -but still, there are also valid plugins that can help further improve the SEO performance of the site.

Ecosystem

WordPress’ ecosystem of themes and plugins is amazing, you really can find anything you need (although themes and plugins are often source of security concerns…as well). The same isn’t true for Jekyll. In most cases you don’t need to write any code, thanks to plugins but also thanks to many themes that automate a lot of stuff with great flexibility.

Genesis and other frameworks

For this site I am using the Genesis framework, and I have also used Thesis in the past. These premium themes are amazing and allow for quick customisation and changes to layouts and more, without having to write any code. With Jekyll, making changes to the layout or things like that mean making changes to the code and rebuilding the site, then deploying again.

Other considerations

With Jekyll I had a super fast, completely static website; it’s hard to beat that. However there are valid caching plugins which, if well configured, can help speed up WordPress quite a bit, so at the end of the day it is not a so big deal as it may appear. Security is another aspect that can be a well known problem with WordPress; however with some good sense and useful plugins and services (both free and paid), it is at least possible to harden WordPress against common attacks. Having said that, I have to admit that I would sleep better at night with a static site generated by Jekyll than with a PHP based CMS like WordPress. But hey, you can’t have everything -I hope I won’t be regretting these words 🙂

At the end of the day, Jekyll is still a young project and I will surely keep an eye on it, but for now I am happy to be back on WordPress. Content is the most important thing, and whatever makes writing content easier gets my vote; at the moment, it is WordPress.