Web & iOS dev – Ruby, Rails, RubyMotion & React

Paul Sturgess

Safer Rebasing With Git

Rebasing a git branch is great way to maintain a clean commit history and it’s my preferred way of getting changes into a feature branch (instead of merging). This blog post will explain how I use it and how I make it safer to use.


Rebasing is dangerous because you are re-writing the branch history!

Imagine someone else has pulled down your branch and then you re-write history – it will really hurt when it comes to combining both your changes.

If your feature branch will be worked on by multiple people, I would strongly urge you do not rebase.

The git book does a great job of describing rebasing in detail, including the pitfalls of rebasing public branches and what to do if you do if you get really stuck after rebasing.

My work flow

For most projects I work on, feature branches are typically only contributed to by one person – so rebasing is ok.

My work-flow for creating a feature branch from master is something like:

$ git checkout -b feature/new_thing
... I make various commits for feature related changes
... Meanwhile, master is also updated
$ git fetch
$ git pull --rebase origin master

This effectively re-writes the history of feature/new_thing to place my commits after those made in master. There’s no merge commit, so it’s really neat and tidy.

I like the idea of opening a Pull Request as soon I start work on a feature. I’ll then make ‘work in progress’ commits as I go and push them up to the remote. This gives people an early chance to review what I’m doing and lessens the chance that my work might get lost if my computer blows up and my backup fails :)

But these commits can be messy and include changes I later revert, as I work on the feature. I think it’s good practice to try and keep commits as logical and concise as is reasonably possible. Ideally they will read like documentation for the feature so that git log is like a story.

So during development, I won’t get too hung up on the commits. But eventually I will use interactive rebase to re-order or squash my commits into shape.

My interactive rebase work-flow is typically:

$ git log
... Find the sha for the last commit I want to leave alone
$ git rebase -i sha-for-commit-to-leave-alone-goes-here

It will then show something like this:

pick f7f3f6d Initial work on feature
pick 310154e Additional work on feature
pick a5f4a0d Finish feature

# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
# These lines can be re-ordered; they are executed from top to bottom.

Just edit pick to whatever action you want to perform and use :wq to save.

Now the next step is to push feature/new_thing to the remote and (other than the first time I push) I’ll need to force push and this is where it gets dangerous!

$ git push -f origin feature/new_thing

This will completely overwrite feature/new_thing whatever state it is in. Too bad if someone else updated it, their changes are gone.

Accidentally type feature/other_thing and you’ve just blitzed the wrong branch!

The safer way to force push

$ git push --force-with-lease feature/new_thing

Force with lease essentially checks the remote branch to see if it’s been updated upstream and if so rejects the push and shows you a nice error message.

Beware that if you fetch, but don’t actually pull in the changes, force-with-lease will not save you!

I want to always use force-with-lease over the standard force but this is long to type so I have a git alias:

$ git config --global alias.pushf "push --force-with-lease"

Now I can safely use:

$ git pushf origin feature/new_thing

Got any git rebase tips? Feel free to contact me on Twitter @paulsturgess

Elixir London Conference 2016

Last week the first ever Elixir conference was held in London and I was lucky enough to attend. It was brilliantly run with lots of great speakers and they’ve even got the videos up online already!

Elixir and Ruby

Elixir is a relatively new programming language that’s gaining in popularity fast, particularly amongst Ruby developers. During the conference they asked the audience to raise their hand if they had been, or are, a Ruby developer and over 75% did (myself included)!

So what’s attracting the Ruby community? Aside from the fact developers love shiny new things, this shiny new thing is different. That’s because Elixir runs on the Erlang BEAM which has been around for decades and was originally developed by Ericsson.

The key-note was from co-creator of Erlang,Robert Virding. It was fascinating to hear him talk about how Erlang was developed to solve the challenges Ericsson was facing building telecoms systems in the late 80’s, early 90’s. It’s amazing that the problems they solved are just as relevant in todays world of online software applications. One of the most high-profile recent adopters of Erlang is WhatsApp.

So what does this have to do with Ruby? Well Elixir inherits all of the characteristics that Erlang is known for:

  • Concurrent
  • Fault tolerant
  • Easy to scale

Often these are the same criticisms levelled at Ruby and Elixir provides an appealing syntax that looks a lot like Ruby.


The icing on the cake for Rails developers looking to transition to Elixir is Phoenix. Phoenix takes a lot of the good ideas in Rails and adds all the benefits of Elixir such as the concurrency and fault tolerance.

Gary Rennie (core member of the Phoenix team) did a great job running through some best practices with controllers in Phoenix. He also explained why umbrella applications are a good idea to logically split your application where it makes sense.

As an aside, I recently came across this article from the creator of phoenix Chris McCord comparing Phoenix channels and Rails action cable which makes for eye-opening reading.


However, it’s not all about web applications and there were a few great talks and demonstrations showcasing embedded systems with Elixir. One of the most interesting discoveries for me was the Nerves Project.

The goal of Nerves is it make it simple for developers to write Elixir to interface with network and input/output devices, embed the code on a memory card, and run it on hardware like a Raspberry Pi.

Ju Liu’s live coding demo involved lots of various sensors (including lasers) and was a particular highlight.

What’s next?

Elixir is very young and there’s clearly lots of enthusiasm in the community. I’m definitely going to be keeping a close eye on the ecosystem that is already growing very quickly. There seems to be a lot of benefits to using Elixir for modern application development.

I definitely want to try writing an Elixir application and wrapping my head around functional programming (when I’m used to Object Oriented programming) is an interesting challenge I’ve been looking for an excuse to take on!

How to Test React Lifecycle Method componentDidUpdate When the Component Props Change

React has many lifecycle methods you can hook behaviour onto, one of which is componentDidUpdate.

This blog will show you how to test this method using react-dom.

Let’s say your component implements componentDidUpdate like this:

import React from 'react';

class YourComponent extends React.Component {
  componentDidUpdate() {

  someFunction() {
    // ...

Now say you want to test that componentDidUpdate calls this.someFunction().

Because the props for the component are set on initial render, and cannot change after that, you can’t just render an instance of the component and manually update the props in your spec.

This is where react-dom comes in. Use it to render the component with an initial set of props and then render the component again with different props.

react-dom will re-render the same instance of the component, instead of creating a brand new one each time.

import React from 'react';
import ReactDOM from 'react-dom';
import YourComponent from 'path/to/your-component';

describe('your-component', () => {
  describe('componentDidUpdate', () => {
    it('calls someFunction()', () => {
      let node = document.createElement('div');
      instance = ReactDOM.render(<YourComponent yourProp={'foo'} />, node);
      spyOn(instance, 'someFunction');
      ReactDOM.render(<YourComponent yourProp={'bar'} />, node);

RubyMotion #inspect Paris Was Loads of Fun

Last week was the RubyMotion #inspect 2015 conference in Paris and not only was I lucky enough to attend, but I was also invited to speak about the RubyMotion football manager game I built: Title Challenge.

Paul at RubyMotion Paris

RubyMotion #inspect is a two-day conference and my talk was scheduled for the second day, which is lucky for me as I missed day one due to protestors spontaneously deciding to prevent the Eurostar from running the day I was due to travel. Fortunately the talks were recorded, so hopefully these will be made available soon!

RubyMotion 4

Laurent Sansonetti announced what is planned for RubyMotion 4 and it sounds awesome:

  • A new REPL to work on the device
  • Cross-platform game framework
  • WatchKit
  • iOS 9 support
  • More work on live code reloading


It was great meeting the RubyMotion community and it definitely feels like an extension of all of the good things from the Ruby and Ruby On Rails communities. Lots of enthusiasm, smart and friendly people doing some really cool things.

For me conferences are all about being inspired and the two talks that stood out were from Amir Rajan and Mark Rickert.

Amir is the genius behind the game A Dark Room which reached #1 in the US App Store. I thoroughly recommend reading his blog which tells the story as he lived it.

Mark told us about his experience quitting his full-time job, selling pretty much everything he owned and living on the road. He now consults on RubyMotion projects remotely, works half as much, makes more money and most importantly is far more happy!

If you get the chance to hear either of these guys speak then make sure you do.

Life begins at the end of your comfort zone

For my talk I discussed the major challenges that were faced in building the game. Highlighting, where I could, lessons learned and things I would have done differently having now gone through the experience.

What I had to say seemed to go down well. The team working on RedPotion have already made changes to the framework inspired by some simple ideas I had for debugging memory issues.

If there’s one point to take-away from my talk though it’s “Life begins at the end of your comfort zone”. If you have an idea, just go for it and don’t be afraid to figure out things as you go along!

Feel free to take a look at the slides for my presentation.

If you have questions get in touch on twitter: @paulsturgess.

WXG Conference – 25th Sept, Guildford, UK

I will also be talking about Title Challenge at the WXG Conference.

It’s a one day conference about web & digital experiences.

Core Data in RubyMotion – Defining Your Schema in Code

One of the things I love about RubyMotion is being able to build applications without having to heavily rely on XCode. I feel far more comfortable in a text editor, where I can actually see the code that makes it work.

Typically Core Data schemas are defined in XCode, with text fields and drop down options used to define the attributes, relationships etc.

Fortunately for RubyMotion developers the fantastic ruby-xcdm allows us to define our schema in code.

This may seem like more work, but one of benefits to defining the schema in code is visibility. With the schema checked into version control, it’s easy to see how it has evolved over time. Who made the changes, when they made those changes and hopefully the commit message might even say why they made those changes.

The ruby-xcdm Readme does a great job of explaining how to set it up. However, I would like to talk a bit about versioning.

If you’re coming from a Ruby on Rails background (as I was) then CoreData doesn’t really ‘do’ migrations like ActiveRecord does. I’d recommend reading up on the term ‘lightweight migration’ in the Apple docs. Essentially for simple things, like adding or removing attributes, it can do these automatically and they can be performed using ruby-xcdm.

To make this work, all you need to do is copy your schema and create a new file. Just make sure you increment the schema number and as long as you have…

task :"build:simulator" => :"schema:build"

…in your Rakefile, then the schema will be built and CoreData will perform the migration.

Ruby-xcdm can handle typical relationship types like has_many, has_one and belongs_to. It also can handle entities that inherit from a base entity - just lookup the abstract: true and parent: options.

Shameless plug

This article is part of a series of blog posts about how I built Title Challenge – A football manager game for iOS.

Others i’ve written include:

Please do check out Title Challenge on the App Store.

Using PaintCode to Dynamically Create Images in the iOS Football Manager Game Title Challenge

One of the important and distinctive visual aspects of Title Challenge is for each football club to have their own shirt and colour theme. The home and away shirts are used on nearly all screens, with the front of the shirts representing a club and the rear of the shirts, with a number on the back, representing a player.

There are over 250 clubs in the database that ships with the game. Each club has 2 shirts and we need several different sizes for different screens. We also had to consider that club shirts will potentially change in both colour and style each season going forward. On top of this, we wanted to support different device resolutions including both retina and non-retina resolutions.

To create a fixed set of graphics of thousands of combinations in varying sizes, styles and colours would have been laborious to say the least and incredibly time consuming to maintain. It also would have enormously bloated the file size of our application.

Shirt Styles

We decided we wanted to be able to dynamically display, hide, colour and scale graphical components with code. This would allow us to display any club shirt on the fly.

The first phase was to decide on some core shirt styles that covered the majority of shirts worn by football clubs. We came up with 6: Plain, Stripes, Hoops, Sleeves, Quarters and Halves. We also have a goalkeeper shirt and a substitute bib used for players on the bench.

Shirt Layers image

The image above shows the different shirt styles in Title Challenge

Vector Layers

After deciding on the styles, Thom, our designer, produced a set of modular vector graphics that could be layered over each other to create any kit style required without duplicating any of the kit elements.

However, those vector graphics weren’t used directly in the game. The shirts you see are entirely generated from code. To achieve this, each individual shirt element was imported into a third party application called PaintCode.

Shirt Layers image

The image above shows the layers that make up a black and white striped shirt with a green substitute bib.


PaintCode is genius, it automatically generates drawing code from vector graphics.

The code to generate a shirt is actually composed of the same graphical modular layers composed on top of one another, but instead of vector graphics, they’re CALayers composed of UIBezierPath line segments with different fills and strokes.

Even the shirt numbers have been generated using PaintCode. We could have used a font, and we did look for one, but we couldn’t quite find the right one. We wanted one loosely inspired by the Mexico ‘86 world cup, but with a modern feel.

In the end it was easier to implement all elements of the shirt using the same code-based method. This was particularly true when we were dealing with scaling and animations on the tactics screen.

Paintcode screenshot

Screenshot of Paintcode with the code in the panel below the shirt vector graphic.

Turn it off and on again

To generate the front or rear of a shirt, we simply show/hide a different collar style. We also show/hide the player number as appropriate. The goalkeeper shirt is just a plain shirt with some extra sleeves added on. For bibs, we simply add the bib layer straight over the top.

Basically we just turn layers on and off and change the colours to produce the shirt combination we want. Taking this approach means that making tweaks are a joy to implement and not a chore to dread.

Another benefit is we were able to include the shirts as part of data editor in the game. So any shirt style can be created completely on the fly using a color picker.

We also changed the shirt style several times during the development of Title Challenge. I have no affiliation with PaintCode, but I’m so glad we used it!

Shameless plug

If you got this far and you’re still wondering what Title Challenge is or you found this post useful and just feel like supporting me – Please do check out Title Challenge on the App Store.

I’ve also written some other posts about developing Title Challenge: Debuging layout issues with RevealApp and How to use Core Data to make your app faster.

Tactics screenshot

How You Can Use Core Data to Make Your RubyMotion App Faster

This is my second post in a series explaining some of the technical decisions behind creating the football management iPhone game Title Challenge. The first post was a short one about using Reveal App as a useful debugging tool for building layouts.

From the outside Title Challenge may appear pretty simple, but under the hood there is a lot more than you might realise going on. Before I talk about why I chose Core Data (or even what Core Data is), let me explain a little bit about the processing the game needs to perform.

Lots of processing means loading screens

Each ‘game week’ you progress, the following needs to be updated:

  • Process player transfers (ensuring these are realistic to each club)
  • Simulate player training (players improve their skill gradually over time)
  • Update all injured players (each week they will be closer to full fitness)
  • Update exhausted players (players get exhausted if they are not rested enough)
  • Check player unhappiness (players can get unhappy at not being played enough)
  • Run scout reports (your scouts will report back on your shortlisted players)
  • Update the transfer list (again ensuring clubs are realistic in who they transfer list)

The key thing is that there could be 6,000+ players to update, with thousands of other related records to update in the database. I wanted this to run as fast as possible to reduce waiting times between game weeks.

While this is going on we show a loading screen. We decided to spend time making these look nice by including colourful player illustrations by Liverpool FC illustrator Dave Will.

Combined with a random humourous/entertaining/interesting quote (of which there are hundreds in the game) it makes waiting as pleasant as possible. Here’s an example:

Loading image  

Measuring Performance with RubyMotion-Benchmark

One way I made the code run faster was to run it, measure it, tweak it. Rinse and repeat. Motion Benchmark is a very, very simple gem but it is easy to use for this very task. It gives you precise control on what code is benchmarked, but this also makes it time consuming to identify what you should be benchmarking in the first place.

Find the bottlenecks in your code

This is where the Time Profiler in XCode’s Instruments tool is incredibly useful. It could be the subject of an entire blog post. In a nutshell it shows the exact time taken for each branch of code, even for each thread. It gives you a full stack trace to work so you can even see which line of code it is. This makes it easy to identify where the biggest bottlenecks are. I would always try and optimise those first to get some quick wins.

Optimise your code without even making it run faster

However, the main point of this blog post is to recommend thinking about how you can optimise your code without even making it run faster. This probably sounds like a an odd statement, but this is where Core Data comes in.

Many developers think Core Data is just another way to persist data and is comparable to using SQLite. Indeed, Core Data can use SQLite to persist data and I use Core Data with SQLite in Title Challenge. However, the fact Core Data can use SQLite is not important and you won’t be writing any SQL to use it. Core Data is primarily a framework for object life-cycle and object graph management.

Coming from a web development background it took me a while to get my head around this. I’ve seen (and written) my fair share of Rails apps tightly coupled to ActiveRecord and the database layer. Using Core Data forces you to understand that persistence is not the same thing as the object graph. So what is “object graph management”? The best way I can explain it, without loads of boring theory, is to tell you how I use it in Title Challenge.

Core Data and the Managed Object Context

I figured out the fastest way to perform the game week processing was to do it while the gamer was not even waiting for it to finish. I decided I wanted to perform the processing while the gamer was picking their team, analysing their squad, scouring the transfer list etc. I’m effectively doing all the processing for the next game week ahead of time.

Core Data allows me to do this because I can take a copy of all the objects in the “Object Graph” ie. all the Clubs, Players etc. (in what is known as a Managed Object Context) and manipulate them as necessary on a background thread. I can perform all the tasks I mentioned earlier (e.g. processing transfers), without any of the changes showing up in the user interface as as the gamer is navigating around the app.

In fact, none of these changes are persisted to disk until the gamer hits continue. This is one of the major differences of Core Data from how you use a database in a web app. With Core Data you make as many changes as you like and at some later date you tell it to save.

Core Data is smart enough to handle the merging of all the changes from the background thread in with the changes made by the gamer on the main thread. The beauty of this technique is it doesn’t really matter how fast/slow my processing code runs, if the gamer is not even aware its running in the background.

This approach has worked really well, especially on older devices where sometimes it doesn’t matter how much you optimise your code, it’s going to run slowly.

Some Complications

It becomes more complicated when the gamer interacts with players that have also changed in the context on the background thread. This is pretty rare in practice, but I’ve written code to handle any conflicts so it resolves them before continuing to the next game week.

The other thing to watch out for is high memory usage. I found as I was processing nearly every player and every club, each game week, these were all getting pulled into memory and not released. Core Data will hold onto objects unless you tell it let go. This is great for performance, but not so great when memory is at a premium. I highly recommend reading up on refreshObject in the Core Data docs. Call this method on objects when you’re finished with them to release them and control memory spikes.

Shameless plug

If you got this far and you’re still wondering what Title Challenge is or you found this post useful and just feel like supporting me – Please do check out Title Challenge on the App Store.

Using Reveal App to Build a RubyMotion Football Manager Game

This is the beginning of a series of blog posts I intend to write on how I’ve built Title Challenge – Football Management.

It’s an iOS game I’ve written in RubyMotion. I’m a Ruby on Rails web developer turned app developer. Before building this game, I had no prior knowledge of building mobile applications.

Hopefully this series of posts will inspire other Ruby developers out there to start building really cool mobile apps.

Reveal App was one of the first third-party tools I downloaded when I started building Title Challenge 18 months ago and I’ve used it nearly every day since. At first glance it might look like a bit of a gimmick to see your app in 3D but it is incredibly useful for debugging.

Reveal App screenshot

I’ve used Reveal to show me when a UIView is tucked behind some other UIView that I couldn’t see in the Simulator. Sometimes a UIVIew might not have a height set or something stupid like that and Reveal would instantly show me.

You can rotate your app round to see it from angles you can’t see in the Simulator.

Another really useful feature is being able to tweak attributes live in the Reveal and the Simulator reflects your changes. For example, you can change the frame of a UIView and see it move in the simulator live.

I’ve got no affiliation with Reveal but I definitely recommend it for App developers.

Tweeting a Screenshot in RubyMotion With UIActivityViewController

The easiest way to allow users to share content from inside your app is to use UIActivityViewController.

Use it when you want to allow the user to:

  • Send a Tweet
  • Share on Facebook
  • Save an image to photos
  • Send an SMS message / iMessage
  • Send an email

In iOS 8 it slides up a panel at the bottom of the screen. The user chooses how they want to share the content. The options are based on the applications they have installed. You can also specify which ones to include/exclude.

Here’s enough code to create an app with a button that brings up the UIActivityViewController, takes a screenshot and allows the user to share it along with some text.

Hopefully the code and my comments are self-documenting enough to make sense.

I figured this out through a combination of the Apple docs and this NSHipster article.

class AppDelegate

  attr_reader :window

  def application(application, didFinishLaunchingWithOptions:launchOptions)
    rootViewController = MyController.alloc.init
    rootViewController.title = 'ActivityViewController Demo'
    rootViewController.view.backgroundColor = UIColor.whiteColor

    navigationController = UINavigationController.alloc.initWithRootViewController(

    @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
    @window.rootViewController = navigationController


# This subclass is not technically required
# It allows you to switch the text based on the type of service it will be shared on
class ShareText < UIActivityItemProvider

  attr_accessor :text

  # The placeholder text
  def activityViewControllerPlaceholderItem(controller)

  # The text that will be inserted into the Tweet / Email / SMS etc.
  # You could easily respond to more activity types if you wanted
  def activityViewController(controller, itemForActivityType: activityType)
    if activityType == UIActivityTypePostToTwitter
      "#{text} #{twitter_handle} #{hashtag}"
      "#{text} #{website}"

  def hashtag

  def website

  def twitter_handle


# This is a simple controller with one button
class MyController < UIViewController

  def viewDidLoad
    button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
    button.setTitle('Start', forState:UIControlStateNormal)
      action: 'button_tapped',
      forControlEvents: UIControlEventTouchUpInside
    button.frame = [[100, 260], [view.frame.size.width - 200, 40]]

  # This method generates the image of the entire screen
  # Note it will not include the status bar
  def screenshot
    window = UIApplication.sharedApplication.keyWindow
    image = UIGraphicsGetImageFromCurrentImageContext()

  # We create an instance of our ShareText subclass
  # Pass it into the UIActivityViewController along with the screenshot
  # The UIActivityViewController handles everything else, all you have to do is present the controller.
  def button_tapped
    tc_share_text = ShareText.alloc.init
    tc_share_text.text = "Check out this screengrab!"
    controller = UIActivityViewController.alloc.initWithActivityItems(
      [tc_share_text, screenshot],
      applicationActivities: nil

    controller.excludedActivityTypes = [



Using NSUserDefaults in RubyMotion

Apple describe NSUserDefaults as “a programmatic interface for interacting with the defaults system”.

It also provides a convenient store for persisting and retrieving user preferences for your application. You can think of it as a key value hash like structure, although it is a bit smarter than that.

Here’s a really simple implementation I’ve been using:

class Cache

  class << self

    def set_default(key, data)
      return if read(key)
      write(key, data)

    def write(key, data)
      NSUserDefaults.standardUserDefaults[storage_key(key)] = data

    def read(key)


    def storage_key_prefix

    def storage_key key

    def cache_namespace
      raise NotImplementedError


class UserSearchSettings < Cache

  class << self


    def cache_namespace



I use it like this:

UserSearchSettings.write("sort_by", "name")
=> true
=> {"user_search_sort_by" => "name"} # note there will be a lot of other key values in the hash
=> "name"

My intention is not to call the Cache class directly and to only use the subclass UserSearchSettings. This forces me to group settings with a prefix defined by the cache_namespace method. This will help avoid accidentally defining the same key name for different values. It also nicely groups related settings.

Each application has its’ own NSUserDefaults.standardUserDefaults so there is no need to prefix the keys with the application name.

This store will persist until the user removes your application from their device.