Ruby Gotcha: Setting default Date, Time and DateTime

If you’re using dates, times and datetimes throughout your appliacation, you might find yourself wanting to specify a default format for each. The default formats come back as follows;

[1] pry(main)> Date.today.to_s 
=> "2014-10-28" 
[2] pry(main)> Time.now.to_s 
=> "2014-10-28 13:07:15 +0000" 
[3] pry(main)> DateTime.now.to_s 
=> "2014-10-28T13:07:19+00:00"

In a commercial web application, it won’t be long before you have a manager knocking on your door asking you to change this format to something a little more human-friendly. It is true that you do have a “strftime” method that allows you to do this:

[1] pry(main)> Time.now.strftime("%H:%M") 
=> "13:41"

But if you’re thinking like a programmer, you will not want to be copy/pasting that format all over your application, you’ll want to change it in one place and for that change to be adopted application-wide. In a rails application you may reason that this could be done in an initializer:

# config/initializers/time_formats.rb 
Time::DATE_FORMATS[:default] = "%H:%M" 
Date::DATE_FORMATS[:default] = "%e %b %Y" 
DateTime::DATE_FORMATS[:default] = "%e %b %Y"

Nice and tidy! So let’s check that out in the console…

[1] pry(main)> Time.now.to_s 
=> "13:45" 
[2] pry(main)> Date.today.to_s 
=> "28 Oct 2014" 
[3] pry(main)> DateTime.now.to_s 
=> "13:45"

Oh dear! Although the Time and Date formats have worked correctly, it appears the DateTime format is broken and is only giving us back the time! This is the gotcha – a datetime will cast its value to a Time and return THAT value, with its associated default format. You can see this from the source code: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html#method-i-to_s

dt_lite_to_s(VALUE self) { 
  return strftimev("%Y-%m-%dT%H:%M:%S%:z", self, set_tmx); 
}

So how do we get around it?

 Solution

There are probably a whole bunch of solutions to this issue, but one is to use one of the more unique features of ruby and monkey-patch the DateTime class:

 
# config/initializers/time_formats.rb 
Date::DATE_FORMATS[:default] = "%e %b %Y" 
Time::DATE_FORMATS[:default] = "%H:%M" 
DEFAULT_DATETIME_FORMAT = "%e %b %Y %H:%M" 
class DateTime 
  def to_s 
    strftime DEFAULT_DATETIME_FORMAT 
  end 
end

Viola

[1] pry(main)> Time.now.to_s 
=> "13:52" 
[2] pry(main)> Date.today.to_s 
=> "28 Oct 2014" 
[3] pry(main)> DateTime.now.to_s 
=> "28 Oct 2014 13:53"

Would be interested to hear about other solutions to this gotcha if anyone else has any ideas.

Moving a WordPress site

If you ever find yourself in the unfortunate position of having to work with wordpress, you may have run into problems when deploying to live. Imagine you’ve got a wordpress site all set up locally and you’re ready to deploy to an expectant client. You might have used a custom theme, entered the content for the client and maybe diddled with the source files a bit, but it’s all working locally so what could possibly go wrong? Surely this is just a case of changing the config file, ftp’ing up the scripts and restoring the database right?

Erm… no.

Lots can go wrong.

  • You might find that once the site is live it still tries to direct you to localhost.
  • You might find you lose all your theme options if you’ve used a paid theme.
  • You might find that some of the content is gone, or hyperlinks within the content are still linking to localhost.

 

A lot of these issues are caused by hard-coded urls going into the database, and these don’t automatically update when you switch to live.  A simple find-replace on the SQL file won’t do it either because some plugins and themes work out their caching by counting the number of characters in a database field, and if you change it without going through the various script hooks you’re going to mess it up. Deploying a WordPress site to live *should* be a doddle, but things can go wrong. Below is the recipe we found works best when doing the first push to live.

Preparation

Make sure the site is working as you want it locally. Once you’re sure it’s working and connected to a database and so on, back up both the site and the DB and keep them safe as the next steps will alter both.

Preparing the database

Save yourself many headaches and get hold of a copy of the wordpress command line tool (http://wp-cli.org/) – installation instructions are on the site.

Once that’s installed, navigate your terminal into the root folder of the site you want to put live and enter the following commands (remembering to add a port to “localhost” if you’re using a different port, and replacing “whatever.com” with your live domain name):

wp search-replace 'localhost' 'whatever.com'

You will then see all the tables that got updated (make sure there’s some numbers in there so you can be sure that it did find/replace the domains!). Next there are two settings in the wp-options table. You can update these on the menu in the wordpress console, but you can’t get to the menu when it’s live because the site uses these settings to direct you to the homepage etc. so you need to change them before going live. If you try and update them in the dashboard of your local version, it’ll break your local version too because THAT will try to get to the live url. It’s a catch-22! wp cli helps again, these two commands will update those settings;

wp option update home 'http://whatever.com'
wp option update siteurl 'http://whatever.com'

Then back it up. That’s the database you’ll restore to live.

Edit the config

Just one last script to go. In the site’s root folder you’ll find a file called “wp-config.php”. There are four database related fields in there that you need to update to the live equivalents, which are “DB_NAME”, “DB_USER”, “DB_PASSWORD” and “DB_HOST”. If you don’t already know these, your hosting provider should be able to tell you (or, it’ll tell you while you’re setting it all up).

Good to go!

With all that done, just ftp the files up to where you want them and import your local database to live. Update DNS and you should be cooking!

I hate wordpress. The irony that this is a WordPress blog is not lost on me :)

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 => "https://github.com/datamapper/dm-#{gem}.git", :branch => 'release-1.2'
end

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!

Interactive fiction – a primer

Okay so I’ve just finished my first interactive fiction, The Scarecrow. I wouldn’t say this was enough for me to call myself an “interactive fiction author” and I certainly wouldn’t call myself a writer (seriously, I’m just this computer nerd from Birmingham!) but I do see it as being a bit of a milestone for me as I’ve been a fan of this genre of writing for some years now. There is a chance that through these posts, some of my friends and followers may have become interested in the genre and so I’m making this post just to give any potential fans a gentle nudge in the right direction.

There’s loads of guide online about how to get an interpreter set up, so I won’t go through that here I’ll just link to this.

In terms of authors – the landscape is pretty rich… it would be dismissive of me to just point you straight in the direction of “the ones you gotta read”, so all I’ll say is that my favorites are Emily Short and Andrew Plotkin. We’ll leave it at that.

The other thing to understand is that these days, the factor that seperates the dogs from the puppies is *quality*. Given that these works are mostly free, that means you have a whole wealth of quality literature right there and readily available, provided by a community who would be delighted if you read and enjoyed their works.

In terms of where to find good IF, this is the joint right here. Either that or a good google search.

Annually, the IF community hold a competition in the month of September (one I hope to take part in next year). The quality is always very high in the competition, this years entries should be appearing here soon. Previous years entries are also available for download from the IF database.

Anyway, hopefully this should be enough to get people started if they’re interested. Peace out \m/

The scarecrow is finished!

My first interactive fiction, “the scarecrow”, is now live for you guys to try out.

Hopefully you’ll enjoy it – the intention here was never to write a great work of fiction, it was initially just to learn the platform… but as I started to build the world I got quite attached to it so quite a lot of care has gone into this. I think enough scene-setting has already been discussed in previous posts, but in my opinion here is how best to experience this story:

1) Grab a nice big glass of red wine

2) Curl up on a couch or some other comfortable place. Dim the lights.

3) Stare at this painting by John Constable

John_Constable_A_Cottage_in_a_Cornfield

4) Imagine the scene in the painting decaying into a rotten, barren landscape.

If by this point you want to know what is in that cottage, click this link and enjoy :)

http://test.laurahogarth.com/The%20Scarecrow/play.html

Feedback is most welcome, particularly if you find yourself getting annoyed or stuck (something I’ve tried very hard to avoid happening). An entire playthrough should take around 20-30 minutes.

Edit: Just in case anyone hasn’t played IF before – remember to examine everything, and if you get lost you can “look” to see what’s around you.

Playtesting interactive fiction is TOUGH!

The IF I’m working on currently clocks in at just over 3500 words, and I’ve been writing it in a linear fashion meaning the first part of the story became playable about a week ago. With typical ill-placed optimism I’ve spent the last week testing it out on various people and have come to the following conclusion: If you present someone with a fantasy setting and ask them “what would you like to do?”, they’re going to say something ridiculous :) And we totally had a laugh too – between lying down in the mud, sitting on a plough in the rain and performing unspeakable acts on a roaming cat, it was a total hoot but it didn’t get me any closer to any decent feedback.

So this is an open plea to anyone who is interested: The first 10 minutes or so of the scarecrow is online now. If anyone would like the link, get in touch. Here are the things I could do with help on;

  • General feedback on the world, is it described well enough (or, too much).
  • General feedback on the system itself. Did you try examining things that weren’t there? Did you type in commands that the interpreter didn’t understand but that you thought were totally valid.
  • Help on ideas for puzzles and texture. Possibly involving a pub lunch / day to brainstorm.

The other thing: If you are genuinely interested in reading / playing through the story, you probably don’t want to be involved in playtesting. Basically, I do need the help, but having been working on this for a few weeks I am totally sick to death of reading the same sentences over and over! This is partly why I need assistance (I can’t tell what’s good or bad any more because I’m too close to it) but equally you should probably bear in mind that if you do help me test/develop, it’ll wreck it for you too.

Anyway, I’ll leave you to mull that over. Cheerio for now!