Writing A Calendar App In Rails Vs. PHP

Some time ago, I wrote a web-based calendar application in PHP, one of my favourite programming languages. This tool would produce a HTML tabular calendar for a four week period, Monday to Sunday, in which the current date (or a user-specified date) fell in the second week (so you’re looking at this week, last week, and two weeks in the future). The user-specified date, for various reasons, would be provided as the number of seconds since the epoch (1970). In addition, the user must be able to flick forwards and backwards through the calendar, “shifting” by one or four weeks each time.

Part of this algorithm, of course, was responsible for finding the timestamp (seconds since the epoch) of the beginning of “a week last Monday”, GMT. It went something like this (pseudocode):

1. Get a handle on the beginning of "today" with [specified time] modulus [number of seconds in day]
2. Go back in time a week by deducting [number of seconds in day] multiplied by [number of days in week] (you can see I'm a real programmer, because I set "number of days in week" as a constant, in case it ever gets changed)
3. Find the previous Monday by determining what day of the week this date is on (clever functions in PHP do this for me), then take [number of seconds in day] multiplied by [number of days after Monday we are] from this to get "a week last Monday"
4. Jump forwards or backwards a number of weeks specified by the user, if necessary. Easy.
5. Of course, this isn't perfect, because this "shift backwards a week and a few days" might have put us in to "last month", in which case the calendar needs to know to deduct one month and add [number of days in last month]
6. And if we just went "back in time" beyond January, we also need to deduct a year and add 11 months. Joy.

So; not the nicest bit of code in the world.

I’ve recently been learning to program in Ruby On Rails. Ruby is a comparatively young language which has become quite popular in Japan but has only had reasonable amounts of Westernised documentation for the last four years or so. I started looking into it early this year after reading an article that compared it to Python. Rails is a web application development framework that sits on top of Ruby and promises to be “quick and structured”, becoming the “best of both worlds” between web engineering in PHP (quick and sloppy) and in Java (slow and structured). Ruby is a properly object-oriented language – even your literals are objects – and Rails takes full advantage of this.

For example, here’s my interpretation in Rails of the same bit of code as above:

@week_last_monday = 7.days.ago.gmtime.monday + params[:weeks].to_i.weeks

An explanation:

  • @week_last_monday is just a variable in which I’m keeping the result of my operation.
  • 7.days might fool you. Yes, what I’m doing there is instantiating an Integer (7, actually a Fixint, but who cares), then calling the “days” function on it, which returns me an instance of Time which represents 7 days of time.
  • Calling the ago method on my Time object, which returns me another Time object, this time one which is equal to Time.now (the time right now) minus the amount of Time I already had (7 days). Basically, I now have a handle on “7 days ago”.
  • The only thing PHP had up on me here is that it’s gmdate() function had ensured I already had my date/time in GMT; here, I have to explicitly call gmtime to do the same thing.
  • And then I simply call monday on my resulting Time object to get a handle on the beginning of the previous Monday. That simple. 24 characters of fun.
  • + params[:weeks].to_i.weeks simply increments (or decrements) the Time I have by a number of weeks specified by the user (params[:weeks] gets the number of weeks specified, to_i converts it to an integer, and weeks, like days, creates a Time object from this. In Ruby, object definitions can even override operators like +, -, <, >, etc., as if they were methods (because they are), and so the author of the Time class made it simple to perform arithmetic upon times and dates.

This was the very point at which I feel in love with Ruby on Rails.

The Flat Is Tidy

Thanks to JTA for his help. Huge thanks to Matt (temporarily minus his hat) for his help: feed the guy oatcakes and rum and he’ll mop your floor! Winnage!

This is, of course, a result of the anticipated sale of the building we live in. The owners of MG’s cafe, below us, and – in fact – the whole building, are selling up and leaving. I’m not sure if this is what they’d planned all along – to buy the building, renovate the café, and sell it at a profit – but it’s at least a little bit inconvenient for those of us who live there and don’t know if and when we’ll have new landlords and whether or not they’ll want tenants (for instance, one of the prospective buyers when the building last came up for sale would have wanted to turn The Flat into a home for themselves).

But hey; The Flat is clean. Come see.

A Jolly Good Fundraiser

Just got back from three days of fundraising for Aberystwyth Nightline, selling hot dogs, burgers, and fries at a stall at the University “Fresher’s Fair”. That was pretty successful.

In other news, a large padded A4 envelope arrived at The Flat today, addressed to Paul. The stamps, letter header etc. all seem to imply that the letter has been sent from NATO‘s “Public Diplomacy Division.” That’s a little alarming.

Beer and curry tonight, usual crew. Meet at 7pm at Scholars or 8:15pm at Cafe All Spice if you want in.

The Aber Effect

Last night really works as a great example of the ‘Aber Effect’. Claire and I went along to Sundeep‘s housewarming party, where she was feeding curry to her housemates and those of us who came along to welcome her back into Aberystwyth. I’d also promised to help sort her computer out with an internet connection, but I’d forgotten to take the network card I’d agreed to lend her.

Having eaten, as some folks were packing up to leave, I suggested that Claire and I go and pick up the network card from The Flat, then come back and install it into Sundeep’s PC. That’s when we heard about Sundeep’s flatmate, who’d managed to lock himself out of his room. So we went back to The Flat and picked up the network card and also a set of lockpicks and a can of oil, and so when we got back Claire was able to install the network card while I picked the lock of the housemate’s room.

Having succeeded in my lockpicking attempt (after some jiggerypokery with the lockpicks and a filed-down Somerfield saver card [knew those things would come in handy]) and opened the room, the housemate offered Claire and I a pint in Scholars, which we accepted. Leaving Sundeep, we joined him and some of the other housemates in the pub for a congratulatory pint each of Old Speckled Hen.

And that’s where we bumped into Matt (in the hat), Andy K, and a friend of Andy’s who will henceforce me known as MOT. Jokes about having to renew him every year aside, we explained our plan to return to The Flat and decant the wine we’ve been brewing in our wardrobe for the last fortnight, and invited them to come join us when they’d finished their drinks. Then, needing to get a head start on them so as to start processing the wine, we set off.

On the way home, we were greeted by two separate groups of strangers, the first of whom overheard our conversation and with whom we briefly debated “the Aber effect”, and the second of whom wanted to use their camera phone to take a picture of Claire and I (although we’re not quite sure why).

We siphoned the wine into bottles, dissolved some fine sugar into it (the yeast had been somewhat overenthusiastic over the first few days and had made the wine slightly bitter and extremely alcoholic), and corked them, right on time for Matt, Andy, and MOT to arrive. We lounged, and drank wine, and were joined by JTA and Gareth, with whom we watched a few episodes of American Dad and listened to some music while the wine kicked in. Which it did, quite remarkably.

So, from a housewarming in Llanbadarn we met a guy who’s lock I picked for which he bought me a pint at a pub where I met some guys I knew and a guy I didn’t who came back to my flat where we drank homebrew wine with some folks who were at the party to begin with. This is the essence of the Aber Effect. And I love it.

Interview With Hayoa Miyazaki

The Guardian ran an interview with Hayao Miyazaki, director of such films as Princess Mononoke, Spirited Away, and Tonari no Totoro. My favourite bit of the interview:

Miyazaki taps a cigarette from a silver case. The Disney deal suits him, he explains, because he has stuck to his guns. His refusal to grant merchandising rights means that there is no chance of any Nausicaa happy meals or Spirited Away video games. Furthermore, Disney wields no creative control. There is a rumour that when Harvey Weinstein was charged with handling the US release of Princess Mononoke, Miyazaki sent him a samurai sword in the post. Attached to the blade was a stark message: “No cuts.”

The director chortles. “Actually, my producer did that.”

scan.co.uk

Ruth wrote:

We are in the process of ordering a new computer. Most of the bits are coming from Scan. Now, their range is lovely, and their postage policy is reasonably sensible, but they have a dumb policy on debit cards.

If you pay with a debit card (instead of a credit card), you can only have the goods delivered to your registered home address. Now, that might seem ok, because where else are you going to want stuff delivered, right? Wrong. You might want thehardware delivered to your place of work because you’re never home during the day. It might be something your buying for a technologically inept relative and you might want it to go to their home, not yours.

Or, like me, you might be a lazy student who uses their mother’s address in far-off North Yorkshire as their home address so they don’t have to change it twice a year.

Things like this which penalise people who don’t use credit cards make me cross. If anyone knows otherwise, please say, but to me it seems that it’s all just a big conspiracy by the banks to make us all use a really, really inferior product.

Anyway. Out of a desire not to have the computer bits go to Yorkshire, we’ve given the money to Dan who’ll be placing the prder with his credit card and getting it sent to our new house in PJM.
—-
On the subject of the post, my mother called me last night to ask for my new address so she could re-direct some letters from the university. So the items in question will have travelled from the campus to PJM (that is, over the road) via North Yorkshire. How very, very silly.

Anyhoo folks, I’ve got to go to work. Oh yeah, and house-warming party tonight, number 72 PJM. Punch and cake provided; if you want anything else, bring it with you.

Forcing people to have deliveries sent to their registered address cuts down on card fraud, which is moderately freqent at mail order computer hardware stores on account of the high value, discreetness, and availability of the goods. It’s not possible to accurately perform such checks on credit cards, but it’s easy to with debit cards.

Many banks give special dispensation on their student accounts; allowing them to – for example – submit two addresses which they will automatically switch between throughout the year – or allow two registered addresses to function for card checks (while still delivering the statements to one). Ask your bank if they can do this, and, if they can’t, write a letter to inform them that there are banks that can. If you’re not willing to let your feet do the talking, there’s no way to let these large organisations listen to you.

There’s no reason not to own a credit card unless you feel you cannot trust yourself to do so – or the banks won’t give you one! For many such cards, there is no interest if you pay them off immediately each month (which can be automated thanks to wonderful schemes like Direct Debit): this increases the flexibility of your purchasing power (particularly when purchasing from overseas) without costing you a penny. On a side note, owning one that you only ever use in this fashion increases your credit rating (which is checked when buying a contract mobile phone, getting a mortgage, applying for credit on a car, or whatever). Just for examples’ sake; if you owned an unused credit card, you could have ordered these computer parts and – odds are – immediately transferred the money from the bank account to the card, thereby giving you the bits sooner.

All of that said, I think I’ve quite aptly (and almost entirely) undermined the sense in preventing expensive goods being delivered only to the registered cardholder’s address, because as we’ve just seen there’s always a way to circumvent such checks by routing the money other ways: this leaves a longer paper-trail (banks and credit companies are, by law, required to keep better records for longer than companies that happen to process card transactions), but is otherwise a sensible way to commit fraud without triggering the little alarm bells that debit cards have hanging from them. So yeah; perhaps Scan should be a little less draconian.

Now Chip-And-PIN in the UK: there’s a flawed, insecure, badly-implemented system.

 

Magic Story

Inspired by Andy‘s PassThePageGame on the RockMonkey wiki – a collaborative storytelling game based on that silly game you used to play at school, I’ve written my own tool:

MagicStory is a collaborative wiki storytelling tool designed to be harder to “run away” with than normal wikifiction. Having read the story, participants can write a suggested “next sentence”, and after three suggestions have been collected a fourth person will be able to choose which one is used. Give it a go!

You’ll need a RockMonkey account, of course, but they’re free and simple to set up.

Stressy Bear

Eek! That’ll teach me to procrastinate! I’ve been putting off various jobs I’ve needed to do for work this last week and a half, thinking that they all needed to be done by Friday this week. But it turns out there’s a mighty amount of stuff that needs to be done by tomorrow morning.

Back to the code…