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

Paul Sturgess

Functional Programming for a Rubyist

Functional programming has piqued my interest for a while – it appears to be reaching a tipping point with the rise of ReactJS, Redux, Elm and ImmutableJS bringing Functional Programming to a whole new set of developers through Javascript.

Elixir is also a functional programming language that’s attracting a lot of the Ruby community.

As an object-orientated Rubyist, I’ve been exposed to some functional programming ideas through Blocks, Procs and Lambdas but when programming in Ruby you’re typically mutating state all over the place.

Pure functional programming works with immutable state.

Coursera

To learn more about functional programming, I’ve just successfully completed the Coursera course Functional Programming Principles in Scala taught by the creator of Scala, Martin Odersky.

Although I didn’t set out to specifically learn Scala, I decided to take the course because the reviews from fellow programmers highly recommended it for learning Functional Programming. I think they were right – it’s a very well put together course and it’s also really tough.

It completely challenges the way you think when you are used to writing imperative code. The course is definitely less about learning Scala and more focussed on the fundamentals of functional programming. Interestingly Scala actually allows both the worlds of functional and object-orientated to co-exist.

Each week you have an assignment to complete that you can upload your program directly from your IDE – there’s an automated test suite that will grade your submission.

Side effect free

So one of the reasons functional programming is gaining popularity is because one of the main cited benefits is that the code is easier to reason about due to being ‘side-effect free’.

It’s this immutability that is at the core of React & Redux, especially for performance.

When a component’s props or state change, React decides whether an actual DOM update is necessary. By using immutable state, it’s very easy to track if an object has changed. The React documentation has a really good detailed explanation on Optimizing Performance.

Scalable

Functional programming languages are often talked about as being highly performant, but what does this mean?

The future trend for computing appears to be more cores and one the way to make best use of the hardware is to run code in parallel. This is where that ‘side-effect free’ code comes into play as makes it a lot easier to run in parallel.

The Future

Functional programming is certainly a completely different mindset for those of us used to object-oriented programs. It will be really interesting to see if it does become the mainstream approach to building web applications. I think I might start trying to apply some functional programming in Ruby and see how I get on.

Further Reading…

How to Write and Test a Redux Container Component for React

As a follow on from my last article about building and testing stateless presentational components, I’m going to explain Redux Container Components.

What is a container component?

A container component is concerned with how things work. This typically involves fetching data, watching the store for updates and updating the store itself by dispatching actions.

Essentially a container component will wrap a presentational component to add behaviour to it.

What does a container component look like?

The container component is created on Line 16 via the connect() function provided by Redux.

You can pass in additional functions to control how you want the state and the actions mapped to the props. These are mapStateToProps() and mapDispatchToProps().

In the example above, I’m using mapDispatchToProps() to setup the addTodo prop that will dispatch the addTodo action we’ve imported. How this is used is entirely down to the AddToForm presentational component and is outside the responsibility of this component.

Note the first argument to connect() is null because I’m not using mapStateToProps(), but the principle is the same as for mapDispatchToProps().

So how is a container component tested?

Container components should be fairly lightweight. There seems little point testing the connect() function, as this is not our code. But we do care that the props are going into our wrapped AddTodoForm component correctly.

So to test this component, all I’m interested in is that the addTodo prop has been setup to dispatch the required action to the store.

The mock store and the Provider are required to render the connected component.

After that I’m just reaching into the component to grab the addTodo prop and calling the function. I’m spying on the dispatch method in the store, that means I can check it’s called with the action that’s formed correctly.

My test for the presentational component AddTodoForm will take care of checking that the prop is actually triggered when it’s supposed to.

How to Write and Test a Stateless React Component

Recently I’ve been learning Redux state container for React apps and it actively encourages ‘stateless’ components. This blog post will describe how these can be written and tested.

Note that you can write stateless components whether you’re using Redux or not!

What is a stateless component?

Redux introduces the concept of ‘presentational’ and ‘container’ components and the major difference between the two is that your presentational components should not be aware of Redux.

Without getting into the details of exactly how Redux works, the consequence of this separation of responsibilities means your presentational components can be fairly simple.

Certainly if they don’t make use of any React lifecycle methods (like componentDidUpdate) they can start life as a simple function that just returns the required output.

What does a stateless component look like?

Below is an example taken from a Todo app, what it does isn’t important. The key thing to notice is that it’s just a function that returns a list item.

Three props are defined onClick, completed and text. There’s no state manipulation.

So how is stateless component tested?

When using ReactTestUtils.renderIntoDocument it will not work with a stateless component – you’ll get an error ‘instance must be a composite component’.

The way around this is to use a component created by extending React.Component to wrap the stateless component. You’ll see in the test below a Wrapper component is created.

Once you’ve done that you can reach into the component to grab out specific DOM elements or other components.

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.

Caveat!

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:

1
2
3
4
5
$ 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:

1
2
3
$ 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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!

1
$ 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

1
$ 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:

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

Now I can safely use:

1
$ 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.

Phoenix

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.

Nerves

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() {
    this.someFunction();
  }

  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);
      expect(instance.someFunction).toHaveBeenCalled();
    });
  });
});

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

Inspiration

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…

1
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

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.