Mr Hyde

A programming blog written in Jekyll

Making a web app with Ruby on Rails (vol. 1)

| Comments

Jewels, trains and web apps

I’m learning how to build web apps using the Ruby on Rails framework. Rails is a framework based on the Ruby language that famously predicates convention over configuration, to help ease the making of web-apps. Share with me in the excitement, adventure and experience points. Hmmm… on second thought, not the experience points.

When I’m not doing science or programming. I dance Argentine Tango and DJ. I also translate tango lyrics. My translation and DJing website is one of several websites doing this. Too bad that it’s difficult to aggregate all these translations into one place and find who has translated what.

Maybe someone could create a database where all these lyrics are organised. Maybe that someone is me. Let’s find out.

Getting our gear together

I’m going to gloss over how to install Rails on your operating system, as there are many a resource on how to do this. If you are on Linux or a Mac, the Rail’s Guides first guide should sort you out. Otherwise, if you are like me and have a Mac, you might need soemthing a bit more involved. If you are on Windows… sorry mate, you’re (almost) on your own! ;–)

Since I’m going to be hosting my app in Heroku, I will also need to have PostgreSQL installed. On the Mac, this is as simple as ‘brew install postgresql’ if you use the Homebrew package manager or with the Postgres.app. Procedures for this will vary across Linux distros, and if you are using Linux you are probably savvy enough to use your package manager.

You will also need to get a Heroku account, and set up some SSH keys on your system, and a detailed walkthrough for setting up a Rails project.

Let it be no secret that I have borrowed heavily from these resources.

The quest begins!

Let’s ask rails to create a new project that we will call ‘tangoLyricsDB’

$ rails new tangoLyricsDB --database=postgresql

Let’s cd inside and see what is there

$ cd tangoLyricsDB
$ ls

We should see a set of files and directories, which make up the application. The most important ones for us initially will be the app folder, which contains our MVC (Model View Controller) files.

Before we can put our app on Heroku, we need to set up some version control with git. If you don’t know git, I’d suggest you do this tutorial.

$ git init
$ git add .
$ git commit -m 'Raw Rails app'

Now we’re ready to put our app on Heroku

$ heroku create

You should see something along these lines:

Creating frozen-samurai-9999... done, stack is cedar
http://frozen-samurai-9999.herokuapp.com/ | git@heroku.com:frozen-samurai-9999.git
Git remote heroku added

Now we can push it all to the cloud:

$ git push heroku master

If it asks you about RSA fingerprints, type ‘yes’.

However, if we go to our app address (i.e. http://frozen-samurai-9999.herokuapp.com/), we see but a warning message and not even a welcome screen.

The reasons for these are manifold. Let’s solve them in turn!

1. rails_12factor

We saw this warning when we first pushed to heroku:

-----> WARNINGS:
       Include 'rails_12factor' gem to enable all platform features

Let’s add this _gem) it to project by opening the Gemfile in a text editor and adding at the end:

# Required by Heroku
gem 'rails_12factor', group: :production

…then we need to install it:

% bundle install

2. welcome page

We don’t have any page on which to land, so let’s harness the power of MVC and create one. First we make a controller:

$ rails generate controller welcome

The let us make a view by creating an index page under app/views/welcome/index.html.erb containing:

<h2>Tango Translation Database</h2>
<p>
  The database is not working yet, but it can tell you the time: <%= Time.now %>
</p>

Then we need to route the user to the right place when we open the app by editing the routes in config/routes.rb and adding a line so it looks like:

Rails.application.routes.draw do
  root 'welcome#index'
  [... Some comments ...]
end

3. migrate the database

You will probably also need to create and migrate your rails database by running:

$ rake db:create db:migrate

Making it all work

Check that it all works locally by running the rails server:

$ rails server

…and visiting the local webpage http://localhost:3000.

If it all works, let’s add the files to the staging area, commit them and push it to the heroku git repository:

% git add .
% git commit -m 'Added rails_12factor and routes'
% git push heroku master

If you now go to your app address you should see your beautiful webpage:

% heroku open

So we have a basic website, in the next installment we will start to flesh it out.

Object Oriented Matlab

| Comments

Time is no object

I’ve been wishing to dabble in Object Oriented Programming (OOP) for a while. Despite understanding the core concepts, however, the jargon and my limited knowledge of OOP-centered languages has kept me at bay. Only 2 problems really that can be solved thus:

  1. Jargon
    • If you can’t beat them, join simplify them. If I can explain the jargon to someone else (you), it will stop being an issue
  2. Knowledge
    • While my knowledge of languages like Python, Ruby and Objective-C is at its infancy, I’m rather familiar with Matlab. And Matlab has (mostly-ignored) Object Oriented capabilities

To learn something well, teach build it

To learn OOP in Matlab, I decided to build a scientific toolbox for analysing multimedia data, since some of my current projects require this.

…well, re-build. The toolbox existed before but used a rather messy set of procedural scripts and functions. If only I could steal acquire the knowledge… Thankfully, there is one or two excellent reference guides that are generally clearer than Matlab’s own documentation.

I made a neat little Visual Analysis toolbox (which remains work in progress) and learned a lot about:

  • Packages
  • Classes
  • Properties
  • Methods
  • Objects
  • Inheritance
  • Dynamic Dispatch

I’ve got a package for you!

An optional thing to do when delving into OOP Matlab is to make a package. A package consists of a folder where all your classes will be stored. Let’s try making one in Matlab.

>> mkdir +package
>> cd +package

Doing it with class

Inside the package, we can start creating class files. Because our new class is excellent, let’s call it superclass

>> edit superclass.m

Inside, we will need to define it, so it will look something like

classdef superclass
   % SUPERCLASS is an excellent class

   properties
   end

   methods
   end
end

Right now our class is rather empty, let’s fill ‘er up.

Properties, the proper way

We can add some properties to our class. What’s nice is that we can hide them from prying eyes and keyboards if needed. We will have a few different ones:

  1. Public:
    • Available to everyone to change inside and outside the class
  2. Protected:
  3. Available to this class and any of its subclasses
  4. Private:
    • Available only to this class

Let’s go back to our class and make some properties, we can have a couple of property blocks:

[...]
   properties
      clothes
   end
   properties (SetAccess = 'protected')
      face
   end
   properties (SetAccess = 'private', GetAccess = 'private')
      heart
   end
   properties (Constant = true)
      MORTAL = true;
   end
[...]

We are letting anyone look at and touch our clothes, they are public because they are not very important.

Our face is a bit more protected, so only our children (i.e. subclasses) can touch it, though in this case everyone can see it (GetAccess remains public).

Our heart has been broken so many times that we keep it private, never letting anyone see or touch it anymore (sniff…!).

Some other things about us are constant and can’t be changed, like the fact that we are MORTAL.

Crystal clear methods

We will need a couple of methods in our class. One of these has to be a constructor. Again, we can make several method blocks.

[...]
   methods
   % This is the constructor
      function obj = superclass(clothes, face, heart)
         if(nargin == 3)
             obj.clothes = clothes;
             obj.face    = face;
             obj.heart   = heart;
         else
             warning('A superclass needs clothes, a face and a heart')
         end
      end
      function obj = program(obj)
         fprintf('Clack, clack, clack\n')
      end
   end
   methods (Access = 'private')
      function obj = sleep(obj)
         fprintf('ZzzzZ\n')
      end
   end
   methods (Static = true)
      function soul()
         fprintf('Some immortal soul will be reincarnated into the next instance\n')
      end
   end
[...]

The constructor method makes an instance of our superclass class. It is a public method, since otherwise you’d not be able to make an instance.

The instance method program is also public, as it’s something that can be accessed (i.e. called) and requested by anyone (i.e. you can, in theory, ask me to program something).

The instance method sleep is private though, as it’s something that can only be accessed within the class (i.e. I’ll decide when to sleep myself!).

The class method soul is static, as it can be accessed without making an object instance (i.e. this example works with the assumption that an immortal soul exists).

I object

There’s little point to make a class unless you want to make objects. Still, let’s try the static method:

>> cd ..   % We need to be outside the package folder to call it
>> package.superclass.soul()    % 'package.' is only needed if the class is inside a package

Without much ado, let’s also make an instance of it:

>> Vader = package.superclass('robe', 1, false);

We have created a superclass object called Vader wearing a robe, having 1 face and no heart. Let’s see if he knows programming…

>> Vader.program();

He does! Let’s make him sleep…

>> Vader.sleep();

Seems like we can’t make him sleep. For our insolence he’s likely to do a Jedi choke. Maybe if he has some heart he won’t do it though…

>> Vader.heart

…we will never know!

The meek subclass shall inherit the earth superclass

Now that we have an excellent superclass, we can make a subclass that will inherit properties and methods from it.

>> cd +package
>> edit subclass.m

Since we want to just see what we’ve inherited, let’s make it simple but add a simple constructor:

classdef subclass < superclass
   % SUBCLASS is a subpar class

   properties
   end

   methods
      function obj = superclass(clothes, face, heart)
         if(nargin == 3)
             obj.clothes = clothes;
             obj.face    = face;
             obj.heart   = heart;
         else
             warning('A subclass needs clothes, a face and a heart')
         end
      end
   end
end

Let’s see if we can make an instance of it:

>> cd ..
>> Luke = package.subclass('robe', 1, true)

Seems like we can’t. The heart property we’d have wished to inherit from superclass is private to the superclass. But we can adjust our constructor:

[...]
      function obj = superclass(clothes, face, heart)
         if(nargin == 2)
             obj.clothes = clothes;
             obj.face    = face;
         else
            warning('A subclass needs clothes and a face')
         end
      end
[...]

Heartless, I know, but we have little choice. Still, Luke is still able to do some of the things his father parent class can do:

>> Luke = package.subclass('robe', 1)
>> Luke.program();
>> Luke.sleep();

So, he’s still has some programming talent but has some sleepless nights in store, since the sleep method from superclass is private. Also, notice that the superclass constructor is called with 0 arguments, in case it needs to do something important. In this case, it just reminds us that Luke is a subclass, since he is heartless.

Dynamic duo dispatch

Let’s power up Luke’s programming to make up for his faults. We can add our own program method that will override the superclass method.

[...]
      function obj = program(obj)
         fprintf('Click, click, click, click\n')
      end
[...]

This should work…

>> Luke = package.subclass('robe', 1)
>> Luke.program();

We can call this differently too:

>> program(Luke);

This is the start of method overloading, which means that we can make the same method call do different things depending on the object that calls it. We can do the same with matlab functions like sum() and plot().

Let’s overload the plot method in our superclass, by adding a new method:

[...]
      function obj = plot(obj)
         image('Vader.png');
      end
[...]

So when we call the plot method on our superclass, it will try to display the ‘Vader.png’ image (I hope you have a good one!), instead of using the matlab plot() function. So after recreating our Vader object anew from our updated superclass, let’s try this method:

>> plot(Vader)

Again, thanks to dynamic dispatch we can have a different plot method in our subclass to instead display the entire Star Wars Episode IV movie in ASCii:

[...]
      function obj = plot(obj)
         unix('telnet towel.blinkenlights.nl');
      end
[...]

If you call this one, get your geeky hat on and some popcorn };–)

Programming baby-steps

| Comments

My first program

I knew nothing about programming until I was 21. It’s not that I was under-age, and programming was not (yet?) prohibited, fun as it is. It’s not that I wasn’t a geek, I was: a Natural Sciences student at Cambridge, using a spreadsheet to track my meager expenses, running Debian (and SuSe, and Mandrake, and eventually Ubuntu) Linux on an already old-ish Acer laptop. It’s just that somehow I had never though of it as a creative activity.

But the summer of 2006 I had little choice. I had to write a program in (forgive me!) Visual Basic to run a cognitive experiment. My supervisor did exactly what was needed to get me up and running:

  • declare some variables
  • write an if statement
  • write a while loop
  • combine them to do a random bubble sorting

5 minutes later he was gone and I was in front of a confusion of lines of code, each shouting for attention. Before too long, I was coding…

Vertical learning cliff

…the cliffhanger above left you wondering. Did he ever learn anything better than Visual Basic..?

The answer is twofold:

  1. No, I learned DirectX first, which is even worse (at least were debugging and documentation is concerned)
  2. Yes, I learned Matlab. Well documented and much easier to debug (but not quite a “proper” programming language)

DirectX took me to designing more visually pretty coloured dots, and then to prettier, if psychedelyc, swirls of cyan and purple.

Matlab taught me modularisation, and DRY (Don’t Repeat Yourself) the hard way. I wrote scripts for the (mostly) “automatic analysis” package for SPM (Statistical Parametric Mapping). This was my first dabbling with XML files, which we used like aluminium, to wrap up analysis modules and build a pipeline scaffold. I picked up a Perl of wisdom or two and some Unreal UDK when working with Virtual Reality (VR) experiments. Finally, I dipped into a bit of R but, tired of pirates, walked the plank.

The plateau phase

Years passed as I workd on my PhD and made a few (unsuccessful) attempts to learn Python. Learned bits and pieces about the bash terminal, compiling from source and other Unix affairs. I dabbled in Version Control packages, and switched from Subversion (SVN) to Github.

Eventually, at the start of 2013 I realised I wanted more from life (and coding), so I took upon myself to stop being a mere coder and become a programmer.

Determined to learn the foundations of as many programming languages as I could, I enrolled in Codecademy and finished all the courses there (HTML/CSS, PHP, jQuery, JavaScript, Ruby, Python). Flat and gray knowledge, but a foundation to build more on top.

High resolution

One half of my 2014 resolution has been to learn to program in iOS. One Xcode installation and a Lovecraft themed To-Do list app later I feel (almost) ready to make a funky mathematical toy.

This blog is the other half, a way to document this learning process. Importantly, the very creation of this blog had to be uber-geeky. No Blogger, or Wordpress or Movable Type would do. Intead it uses Github Pages, Jekyll and Octopress.

351 days to go…