Cocos2d and our iPad app

February 13, 2011 § Leave a comment

[tweetmeme]

Cocos2d is a fantastic library that has helped us to create our first iPad app – an interactive companion book to Susie Cornfield’s Dekaydence series.

We wouldn’t have been able to do it without the help of this library and it’s friendly and helpful community – massive thanks to all the contributors that make it such a great library to use.

To give back to the community, We have offered up our office space to hold the next Cocos2d London User Group on March 3rd.  Information can be found on the Cocos2d forums and on lanyrd.

Heres a short video of The Lost Journal iPad app:

London Taxi Meter estimates 5,000 fares a month

January 3, 2011 § 2 Comments

[tweetmeme]

A month ago we released an updated version of Conjure’s London Taxi Meter which has continued to go from strength to strength. We are very pleased to announce that during December, we helped over 5,000 people estimate the cost of their cab journey!

Semi-modal dialog views for iPhone

August 28, 2010 § 4 Comments

[tweetmeme service=’bit.ly’]

Switching views using the modal dialog paradigm is fairly straightforward, but I had a modal dialog that didn’t require the whole height of the window. Having a full-height window for one control just looked stupid. I’d seen a few times modal views sliding up from the bottom (a bit like a UIActionSheet) and wanted to replicate something similar (see image left). After trawling the internet, I found this post which explained how to do what I wanted.

I used almost exactly the same technique, except the view I created in Interface Builder was only as tall as I needed (see image right).

In the view that I was going to cover, I also added a UIView with a black, transparent background that covered the entire screen and was on top of all the other components. I could then animate the transparency of this to create a “mask” that hid the components on the background view while the dialog was displayed.

The code from the post mentioned above was then used to hide and show the dialog:

- (void)showMyModalView {
	MyModalViewController *controller = [[MyModalViewController alloc] initWithNibName:@"MyModalView" bundle:nil];

	// move the modal view off the screen
	CGPoint viewCenter = controller.view.center;
	CGSize screenSize = [UIScreen mainScreen].bounds.size;
	controller.view.center = CGPointMake(screenSize.width / 2.0, screenSize.height * 1.5);;
	// add the modal view to the current window
	MyAppDelegate *delegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate;
	[delegate.window addSubview:controller.view];

	// animate the showing of the modal view and show the mask
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5];
	controller.view.center = CGPointMake(viewCenter.x, screenSize.height-viewCenter.y);
	mask.alpha = 0.8;
	[UIView commitAnimations];

	[controller release];
}

- (void)hideMyModalView {
	CGSize screenSize = [UIScreen mainScreen].bounds.size;

	// animate the hiding of the modal view, and fade the mask
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5];
	controller.view.center = CGPointMake(screenSize.width / 2.0, screenSize.height * 1.5);
	mask.alpha = 0.8;
	[UIView commitAnimations];
}

Note: “mask” is just a solid-black UIView on top of the view which is usually transparent.

A little late on the fizz buzz problem

August 27, 2010 § 9 Comments

[tweetmeme service=’bit.ly’]

My two cents in Ruby.  Extending the Fixnum class allows you to call .to_fizz_buzz_string instead of .to_s if you want the fizz buzz version of an integer rather than the usual string version.

#!/usr/bin/ruby

class Fixnum
  def Fixnum.fizz_buzz_entities
    {
      3 => 'Fizz',
      5 => 'Buzz',
    }
  end

  def to_fizz_buzz_string
    fb = Fixnum::fizz_buzz_entities.inject('') { |result, kv| result << kv[1] if (self % kv[0]).zero?; result }
    fb.empty? ? self.to_s : fb
  end
end

(1..100).each { |i| puts i.to_fizz_buzz_string }

Inspired by The Fizz Buzz problem and diving in too soon and The Fizz Buzz Problem.

Strange problems with ruby-debug (rdebug) after installation of Ruby Enterprise (REE)

June 7, 2010 § Leave a comment

Some of us had some troubles with ruby-debug after upgrading to Ruby Enterprise Edition.  One of the issues was with ‘debugger’ statements within the source code causing the debugger to break, but to report line numbers multiplied by two!

Continue reading Strange problems with ruby-debug (rdebug) after installation of Ruby Enterprise (REE) on my old blog.

Essential TextMate Plugins

June 4, 2010 § Leave a comment

Our development team has now got upwards of 20 man-years experience with TextMate so we thought it would be a good idea to share with you the most useful bundles we’ve come across so far. If you feel there are any glaring omissions, then please leave a comment!

AckMate
http://github.com/protocool/AckMate

If you have worked with TextMate for any period of time, you will come to realise that the Find in Project is woefully inadequate. Fortunately, the plugin architecture means that a much superior alternative is available. Most programmers will have come across Ack, but for those of you who haven’t, it’s a technology that harnesses the power of Perls’ regular expressions and is very good at working with large trees of heterogeneous source code.

Once installed, the selected folder in the project drawer will be the root of the search and Ctrl + Alt + Cmd + F will open up the AckMate window. Results are displayed with a line above and below the matching text giving some context to the results.

See http://betterthangrep.com for more information on Ack.

RubyAMP
http://www.ruby-lang.org

RubyAmp adds a few productivity aids to TextMate. The most useful I find being the “Complete across tabs” (Ctrl + ; ). This works in a similar way to how pressing Escape will autocomplete within a file and provides the same functionality across multiple open files showing a popup list of possible matches, with the first 10 mapped to the number keys. Another really useful feature common amongst IDEs for statically typed languages is the ability to easily jump to method definitions, classes etc by using shortcuts.

ProjectPlus
http://ciaranwal.sh/2008/08/05/textmate-plug-in-projectplus

This bundle adds a few bells and whistles to the project drawer in TextMate. Instead of the standard fly-out drawer, ProjectPlus gives you a pane which remembers the state of your project tree and open tabs between opening and closing projects. One key feature adds SCM badges to the files and folders in the project drawer giving a quick and clear indication of files and folders within your SCM. Other small features include: “Show folders at top” instead of the default alphabetical order, “Sort by filetype”, Finder colour labels and QuickLook.

Installing Bundles

To install a .tmbundle file, place it in ~/Application Support/TextMate/Bundles and then select “Bundles > Reload Bundles” from TextMate. If you use TextMate with multiple OS X user accounts then .tmbundle files can copied to /Application Support instead.

Final note

On the subject of TM additions, by far my favourite syntax colouring scheme is the one used by railscasts.com available from here. Also, if you use code within presentations, it’s often really useful to copy blocks of code whilst retaining their style when pasting into another application. This is easily achieved using “Copy with style” available from here.

Original article Essential TextMate Plugins.

Take care when writing to files using puts

February 5, 2010 § Leave a comment

For writing text files; especially line by line, it’s perfectly acceptable to use puts. But, be warned that this will append a line break after the data being written. This behaviour is not desirable when working with binary files, when IO::write is a better choice to avoid unwanted line break characters.
For example:

file = File.new('temp.file', 'w+')
file.sync = true

while data = get_data
  file.write data
end

file.rewind

Original post: Take care when writing to files using puts.

onbeforeunload event and differences between browsers

January 19, 2010 § Leave a comment

The [recently in webkit] supported onbeforeunload window event can be very useful to inform the user if they are about to loose some data which they haven’t saved yet etc. So, in your method that the event calls you will probably have some logic to decide if the method should return or not (returning a string from the method causes the message to be displayed to the user).

This is all very well and good, but we came across an instance where outside of this method we wanted to set a variable to stop the message, request a new window.location (to download an file) and then turn the variable on again. The code looked a little like this:

window.shouldWarnTheUser = false;
window.location = '/download/my.file';
window.shouldWarnTheUser = true;

And the onbeforeunload callback looked a bit like this:

window.onbeforeunload = function() {
  if (window.shouldWarnTheUser) {
    return "Some warning!";
  }
}

This gave us different results between different browsers and took some time for us to figure out why.

Consider the following example:

window.onbeforeunload = function() {
  console.log("3");
}

console.log("1");
window.location = '/download/my.file';
console.log("2");

Question:
What order do the numbers get logged out?

Answer:

  • Webkit: 1, 2, 3. (Safari 4.0 and Chrome 4.0 on OS X 10.6.2)
  • Firefox: 1, 3, 2. (FF 3.5 on OS X 10.6.2)

Both understandable depending on how you think the events are fired

  • Internet Exploder: 3, 1, 2. – What?! (IE 8 on Vista)

Original post: onbeforeunload event and differences between browsers.

Keeping custom Rails model validations DRY

January 18, 2010 § Leave a comment

There are a few blog posts on writing model validators – this is another one which follows the DRY (don’t repeat yourself) philosophy.

Suppose you want to check that an attribute value is present in a table of tags in our database. Now, this isn’t a particularly good use case as you could use validates_inclusion_of, but lets assume that we want to DRY that up a bit.

Let’s write the validation to make the following work:

validates_inclusion_in_tags :primary_tag, :secondary_tag

The validation method would look a little bit like this:

def validates_inclusion_in_tags(*attr_names)
  validates_each attr_names do |record, attr_name, value|
    acceptable_values = Tag.find.all.map{ |obj| obj.name }
    record.errors.add(attr_name, "does not match any available values") unless acceptable_values.include?(value)
  end
end

What’s going on here? Firstly we attach our custom validation to the model using validates_each. This runs the block for each of the attribute names (symbols) in the attr_names array (note that we have used the splat operator in our argument list to flatten the arguments into an array so we can pass a list of attribute to validate). The validation block is passed three arguments: the record being validated, the attribute name (as a symbol) and the current value of the attribute that is being validated. We then execute a find on our Tag model to get an array of AR records which we then map to extract the name of each object into an array. Finally we associate an error to the attribute that we are validating if its value is not in the list of acceptable values we have created.

To make the validation method a little more configurable and a little more generic we can allow the validation method to be called with a hash of options. Maybe we want to define a different error message, supply a different model to validate against, or supply a different attribute to be selected from our model. This can be easily achieved like so:

def validates_inclusion_in_model(*attr_names)
  # Set up any default configuration options and merge on any passed to the validation
  configuration = {
    :message => "does not match any available values",
    :model => Tag,
    :model_attribute => :name,
  }.merge(attr_names.extract_options!)

  validates_each attr_names do |record, attr_name, value|
    acceptable_values = configuration[:model].find.all.map{ |obj| obj.send configuration[:model_attribute] }
    record.errors.add(attr_name, configuration[:message]) unless acceptable_values.include?(value)
  end
end

You’ll note that the default configuration options are merged with the configuration options that were passed into the validation method. This (very common) technique makes use of the extract_options! method which returns either the last item of an array if it is a Hash or an empty Hash.

OK, that’s all good – what’s the best way to get this method available to our models. The best ways are as follows: Either create a validators.rb file in config/initializers and open up the ActiveRecord::Base class like so:

ActiveRecord::Base.class_eval do
  # define your validation methods here
end

Or, the way I prefer is to to create a validations.rb file in your lib directory and use the following code:

module Validations
  # Extend the caller with the ClassMethods module
  def self.included(base) # :nodoc:
    base.extend ClassMethods
  end

  module ClassMethods
    # define your validation methods here
  end
end

Now you can pick and chose which validations are available to your models rather than extend every model that inherits from AR Base by using:

class Person < ActiveRecord::Base
  include Validations
end

Of course, if all of your AR models inherit from a shared base class which in turn inherits from AR Base, then you could also include the validations model at your shared base model level to give all your models access to your new validations.

Note on performance

The validation method here would load all the Tag records into AR objects in memory just to throw them away again. Also, this problem is exacerbated if you were to compare two attributes against the list as the objects are loaded for each call into validates_each.

Original post Keeping custom Rails model validations DRY.

Datatypes in Javascript – setting the record straight

December 23, 2009 § Leave a comment

It’s a question that often comes up and there are many places on the internet that give an inaccurate answer, so here’s the real-deal.

Continue reading Datatypes in Javascript – setting the record straight on my old blog…

Where Am I?

You are currently browsing the Code category at Fringley's Blog.