Preparing Scalable Models

The word scalable gets thrown around a lot, usually in terms of databases or web back ends, but client-side code can easily become unscalable as well. For instance, if we wanted to add more attributes to our User, we’d have to make changes in three places: our class definition, our controller, and where we instantiate our objects. In a world where engineers move fast, having all this overhead can be a big time sink.

I wouldn’t bring this up if there weren’t a better way. We’re going to use a nice Ruby trick that lets our models become more flexible and readies them for a typical API. In user.rb, change our three attr_acessor lines into this:

 class​ User
  PROPERTIES = [​:id​, ​:name​, ​:email​]
 attr_accessor​ *PROPERTIES

Nifty, right? Now we have one data structure containing our desired properties, instead of multiple independent lines. This lets us refactor code that should apply to all properties into more loops like PROPERTIES.each. For example, we can now make our User initializable with a hash.

 def​ initialize(properties = {})
  properties.each ​do​ |key, value|
 if​ PROPERTIES.member? key.to_sym
  self.send(​"​​#{​key​}​​="​, value)
 end
 end
 end

This lets us initialize users in one line instead of needing one line for every property. Plus, when we add new properties, the initializer code still works. Let’s start updating our old code to use this concept. In UserController, change our properties from being hard-coded to using User::PROPERTIES.

 last_label = ​nil
»User::PROPERTIES.each ​do​ |prop|
  label = UILabel.alloc.initWithFrame(CGRectZero)

While we’re at it, let’s change how we created the @user instance variable in AppDelegate.

 @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
 
»@user = User.new(​id: ​​"123"​, ​name: ​​"Clay"​, ​email: ​​"[email protected]"​)
 
 @user_controller = UserController.alloc.initWithUser(@user)

If you run our app now, nothing looks different, but under the hood we’ve made some important changes. Just to show how useful this is, let’s add a new phone property to User so that we can see how we just change the input when creating a new object.

 class​ User
» PROPERTIES = [​:id​, ​:name​, ​:email​, ​:phone​]
 attr_accessor​ *PROPERTIES
 @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
 
»@user = User.new(​id: ​​"123"​, ​name: ​​"Clay"​,
»email: ​​"[email protected]"​, ​phone: ​​"555-555-5555"​)

Once you run rake, you’ll see that we now have a matching UI element for our new property without having to add new code in the controller. This is a great example of how smart(er) models can save us time, but what if we wanted to edit this data?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset