Skip to content

Simple, Clean Persistence in Rubymotion with motion-persistable

Gavin Morrice

Written by Gavin Morrice on Jun 11th, 2014

While working on a current iOS app I was using the very useful BubbleWrap gem for persisting values within a few classes. While BubbleWrap is great, but I found that having to call App::Persistence[] throughout my app wasn’t ideal.

For one, using strings as the persistence keys is not DRY - you change the key in one place, you have to change it all over. motion-persistable is a simple gem that provides a wrapper around BubbleWrap’s persistence (which uses NSUserDefaults under the hood) to add attribute accessor macros for persistable attributes. 

Using it is as simple as:

class User include Motion::Persistable

  attr_accessor :name

  # This is the motion-persistable part

  attr_persisted :email

end

@user = User.new("bodacious")

@user.email = "[email protected]"

# ... later

@user = User.new("bodacious")

@user.email # => "[email protected]"

For class methods: 

class User

  class << self

    include Motion::Persistable

    attr_persisted :use_count, 0

    attr_persisted :email, "[default]" do |value|

      # This block is executed when a new value is set
      mixpanel.people.set(email: value)

    end

  end

end

 User.email = "bodacious"

User.email # => "bodacious"

The gem is available on Github


Gavin Morrice

This post was written by me, Gavin Morrice

I’m a web developer here at Katana Code, where we've helped dozens of startups, charities, and SMEs launch effective and elegant websites to market.

We would love the opportunity to help you too!

Get in touch today