Exploring RubyMotion Libraries

We whipped up a pretty interesting app using a relatively small amount of code; however, we also used some vestigial Objective-C patterns that look obviously out of place. This is one area where the RubyMotion community is stepping up and wrapping un-Ruby code into more idiomatic structures. Several libraries and RubyGems[11] are available that could have helped us manage our views.

For example, Sugarcube (https://github.com/rubymotion/sugarcube) would have allowed us to replace those long animation method names with very concise functions such as fade_out and move_to.

 last_view.fade_out { |view|
  last_view.removeFromSuperview
 }
 
 other_views.each ​do​ |view|
  new_origin = [
  view.frame.origin.x,
  view.frame.origin.y - (last_view.frame.size.height)
  ]
 
  view.move_to new_origin
 end

Much better, right? And for more complex apps, the Teacup library[12] allows you to construct views using CSS-esque style sheets. Our blue boxes might have Teacup style sheets defined like this:

 Teacup::Stylesheet.new ​:app​ ​do
  style ​:blue_box​,
 backgroundColor: ​UIColor.blueColor,
 width: ​100,
 height: ​100
 end

Third-party libraries like these are helping RubyMotion become more than just an Objective-C/Ruby mashup. As you can see in the previous examples, they can dramatically change how we express what we are trying to accomplish in code. Later in Chapter 4, Representing Data with Models and Chapter 7, Example: Writing an API-Driven App, we’ll actually use some third-party RubyMotion frameworks to simplify otherwise complex elements of our apps.

But even without those niceties, we’ve gone from an empty app to an interactive, animated UI in the span of a few quick examples. There are far more included UIView subclasses than we have time for, but the ones we’ve covered should make those a cinch to learn when the time comes.

By making a slightly more ambitious app, we have also gotten a chance to see how the Ruby language can make our iOS development lives a little easier. Take my word for it, RubyMotion methods such as Array#select and string formatting ("#{ruby_code_here}") are more concise than their Objective-C counterparts. Then again, we still have some very non-Ruby practices that leave much to be desired, such as UITextField’s delegate pattern.

In the course of working on views, our AppDelegate got pretty crowded with all kinds of code: helper functions, button callbacks, view creation...the works. Real apps have much more robust organization in the form of controllers, which we’ll cover now in Chapter 3, Organizing Apps with Controllers.

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

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