At the last DTC ruby group meetup there was a request to post slides & code from presentations. I can only speak for myself but I will try & post my presentations.

You can view the code I wrote for the presentation at https://github.com/bobfirestone/coin_toss_rubymotion_demo

rubymotion:

It’s very sunny here in San Francisco, California, and we are super excited to give you a first sneak peek at the next major version of RubyMotion, numbered 3.0, which will be released later this year!

Android Support

RubyMotion 3.0 features support for a new mobile platform: Android. You can…

client side or server side web apps

The current hotness in web development is client side JavaScript applications. It seems like every week there is a new framework announced on hacker news that will revolutionize the way the web works. I will concede that things like meteor.js are impressive.

Do you really need it?

A lot of what I see getting built with angular, ember, backbone or (insert this weeks hotness) are not right for this methodology.

1. Is your data visitor unique?
2. Does your data change faster than the length of a page visit?

If you can’t say yes to both questions you are probably going to be better served server side.

How Much Test Coverage Should I Have? 20-30% is Probably Plenty

Start talking about Test Driven Development (TDD) and you are going to get a reaction out of people. Ranging from religious zealots that have tests for every method in their app to contempt and belief that TDD is for idiots. Automated testing is a good idea and like all good ideas it can be taken too far.

My general thought on TDD is most people write too many tests and have tests for things that shouldn’t be tested directly. The key words there are “tested directly.” If you follow the single responsibility principal and are writing short methods what you end up with is iceberg classes. You have a few public methods and a lot of private methods. Like an iceberg you have a little bit you can see above the water and a lot you can’t see below the water line.

When it comes to writing tests I am a firm believer that you should only be writing tests for the public methods. Public methods are ultimately the important ones from an object messaging standpoint and what needs to communicate with other objects.

As a user of a class when I call a public method my concern is the return value. If the return value is correct I really don’t care how it gets calculated.

class MyClass
  def one
    1
  end
end

Or

class MyClass
  def one
    one_x_one
  end
  private
    def one_x_one
      1 * 1
    end
end

A test

describe MyClass do
  subject{MyClass.new}
  describe '#one' do
    its(:one){should eq 1}
  end
end

Both versions of MyClass result in a passing test. A test on a public method is indirectly testing any private methods it relies on to generate its return value. A test of MyClass#one will catch any change made to the MyClass#one_x_one private method will be reflected in the result. If we change our private method to return an unexpected value the test will break.

class MyClass
  def one
    one_x_one
  end
  private
    def one_x_one
      1 + 1
    end
end

Changing one_x_one from 1 * 1 to 1 + 1 will break the test and we now know that there is a problem.

Realistically about 1/4 of your methods will be tested directly.

Why is testing the private methods bad?

100% test coverage is a noose around your neck when it comes time to refactor. Every code change you make necessitates a corresponding change to the tests suite. Effectively doubling the work for a little result. On top of doubling the time to make changes every test takes time to run. Having a bunch of unnecessary tests increases the amount of time it takes the test suite to run.

There are always going to be exceptions to every rule and never test private methods is no different. Sandi Metz, the author of Practical Object-Oriented Design in Ruby has publicly spoken of writing temporary tests on private methods. The example she gave was debugging a tough problem and you needing to verify what methods are returning at various points in the call chain. Sandi says to write tests for the methods, verify they are working as expected and once the problem is solved delete the tests.

Final Thoughts

An automated test suite is really an early warning system to let you the developer know something is wrong. A failing test says some piece of code is not working as expected. The greatest test suite can’t prevent changes from breaking other code. Having tests can make us aware that what we are doing is having unintended consequences and needs to be looked at closer.

Why Enterprise Fails at Agile

How is it that a startup can come out of seemingly nowhere, build, launch and iterate their app 3 or 4 times before an enterprise can get to a public beta?

The reason enterprise moves so slowly is there are too many cooks in the kitchen. Every person with a title has a list of features or some bell or whistle they want to see included. These features get implemented because “that’s what the boss wants.”

The difference between a startup and enterprise comes down to the startup is building what the customer wants and the enterprise is building what the boss wants.

Being agile is not about the tools you use or the language your app is written. For an enterprise to start thinking and acting like a startup then it needs to stop building features that the users are not asking for.

A feature that is a “nice to have” is probably a “don’t need”.

Ruby Forwardable: Delegation with plain old ruby objects. No rails required

In OO design using composition is considered preferable to class inheritance. In the ruby world this is especially true because ruby only allows for single inheritance.

Using composition can lead to some vary ugly looking method chains where an Object is traversing its way through the multiple objects that it is composed of.

For example: from my_object you might need to access property_x that lives nested object two objects away.

$ my_object.other_object.another_object.property_x

You can chain a bunch of calls together and get there. Traversing objects this way is a bit off-putting. Also if you are doing this in one spot you are probably doing it in more than one spot and that is potentially error prone.

Passing a method call from one object to another to do the work is a common thing to want to do so the ruby standard library gives us the Forwardable module. Using Forwardable allows ruby to delegate a method called on ObjectA to another object ObjectB.

A Simple Example

Starting with a From and a To class

class From
  attr_reader :to
  def initialize
    @to = To.new
  end
end

class To
  attr_accessor :count
  def initialize
    @count = 0
  end
  def inc
    self.count += 1
  end
end

We can create a new From object and get to the count parameter and inc methods through the To object.

$ from = From.new
$ from.to.count
> 0
$ from.to.inc
> 1
$ from.to.count
> 1

It would be better to be able to call from.count and get the count and from.inc to increment the count. This is easily done by extending the Forwardable module in our From class.

require 'forwardable'
class From
  extend Forwardable
  def_delegators :@to, :count, :inc
end

Now from the console we can do this

$ from.count
> 1
$ from.inc
> 2
$ from.count
> 2

What if instead of count I wanted to call the method total?

That is easy. def_delegators allows us to pass an object and any number of method calls we want to delegate and it uses the existing method name to do it. Using def_delegator we have to do them one method at a time but we have the option of giving methods aliases.

def_delegator :@to, :count, :total
def_delegator :object, :method, :alias=method

def_delegator the :alias parameter is optional. If there is no alias parameter given it defaults to using the given method.

Double Delegating: a more complex example

How about delegating to a nested object? In this example we have a store that goes through a middleman to access the inventory of a warehouse. Standard chaining to get the inventory would look like this:

store.middle_man.warehouse.inventory

Instead of going through the chain and calling inventory it would be better to be able to call something directly on the Store object to get the information. Also calling store.inventory could easily be confusing to someone new coming in to the code. Something like .in_warehouse would be more descriptive of what the value getting returned actually is. To be able to call .in_warehouse we need to do two delegations.

First from MiddleMan into Warehouse to expose inventory. Second from Store into MiddleMan to access inventory and alias it as in_warehouse.

class Store
  attr_accessor :middle_man
  extend Forwardable
  def initialize
    @middle_man = MiddleMan.new
  end
  def_delegator :@middle_man, :inventory, :in_warehouse
end
class MiddleMan
  attr_reader :warehouse
  extend Forwardable
  def initialize
    @warehouse = Warehouse.new
  end
  def_delegator :@warehouse, :inventory
end
class Warehouse
  attr_reader :inventory
  def initialize
    @inventory = 100
  end
end

Bringing it all together

$ store = Store.new
$ store.in_warehouse
> 100

More Responsive Layouts

Responsive design is a good tool for refining the way a site looks on different devices. Most responsive layouts the changes are handled in the browser by CSS and JavaScript. Having the browser handle it does make it simple to implement. The downside is you are still loading the same quantity of content to the browser even if you are not going to show everything. Out of the box Rails 4.1 adds ActionPack Variants which gives an even more fine grain control over how the page renders. Using ActionPack variants you can have different view files that render for the same controller action based on the users device.

Lets say you have an Articles controller. For desktop users you want to render a carousel of featured articles, for a tablet user a single image with the first featured article and on phones a list of the featured articles. In a traditional responsive design you can make this work but the browser is going to load all three versions and use a show or hide based on the dimensions. A good solution for what the user sees, a bad solution for the users bandwidth.

Rails 4.1 adds a new feature called ActionPack Variants. In our rails 4.1 app our views/articles directory we can have multiple view files that will selectively render based on the type of device the user has. In our example we would have three index views: index.html.erb, index.html+tablet.erb, index.html+phone.erb.

For this to work we need a before filter in the controller action. Unless you are only going to be using this on a single controller this should probably go in the application_controller.rb

class ApplicationController < ActionController::Base
  before_action :detect_device_type

  private

    def detect_device_type
      case request.user_agent
      when /iPad/i
        request.variant = :tablet
      when /iPhone/i
        request.variant = :phone
      when /Android/i && /mobile/i
        request.variant = :phone
      when /Android/i
        request.variant = :tablet
      when /Windows Phone/i
        request.variant = :phone
      end
    end
end

User agents with android is less clear than with apple devices. Android device manufacturers are recommended to have “mobile” in the user agent string for phones and not have it for tablets. For windows it looks like there is not a way to tell if a device is a tablet. For touch enabled devices they do include touch in the string. That doesn’t really help much with the touch enabled laptops and desktops.

If you have the correct view files the respond_to block is optional. Rails is smart enough to know if the variant is phone and there is no phone layout to fall back to the standard view as a default.

If you want to use a respond_to block for our index it would look like this

respond_to do |format|
  format.json
  format.html               # /app/views/articles/index.html.erb
  format.html.phone    # /app/views/posts/index.html+phone.erb
  format.html.tablet     # /app/views/posts/index.html+tablet.erb
end

In the respond to block you can add a block to individual formats to change the behavior

format.html.tablet { redirect_to "http://www.bobonrails.com" }

You can read more about ActionPack Variants in the 4.1 release notes http://edgeguides.rubyonrails.org/4_1_release_notes.html#action-pack-variants

Emacs Adventure

I have been using sublime text 2 for a couple of years and overall I am a happy camper. I am not happy about the upcoming switch from 2 to 3. The switch is primarily driven by the need to switch the underlying python version from 2 to 3 and that breaks things.

When sublime text 3 exits beta I am jumping ship. My criteria for the new editor are stability and extendability. Stability because I want to minimize the need to switch again for a long long time. Extendability because a programmer should be able to program their editor.

The contenders: RubyMine, emacs and vim.

RubyMine 6 was just released and to be honest it had no shot. I bought a license last year during the jet brains mayan calendar the world is going to end sale. After playing with it for a while it was way too heavy. A lot of the features offered are pretty cool and can come in handy when you need them; but seem to get in the way when you don’t. There are plenty of developers who like the full IDE experience I just don’t fall in that category. Also it needs java to run and that is not a plus in my book.

Vim and emacs both meet the two primary criteria of being stable and extendable. Both are downright ancient with origins from the mid 1970’s. The core functionality is stable. Each has their own language for creating new functionality Vimscript and emacs lisp.

Who wins? Emacs.

I am going with emacs because after using both I want to use emacs. With vim I kept going back to sublime anytime I ran into something that wasn’t clear. With emacs the urge to run back to what I already know was significantly less.

Now that I have picked my horse it is time to ride. From time to time I will be posting tutorials and links to emacs related stuff. Mostly so when I need to do it again in the future I can easily find it.

TODO:

  1. Get comfortable with the keyboard navigation and learn the basic keyboard shortcuts.
  2. Get a combination of plugins to build my workflow.
  3. Learn emacs lisp and start building macros and plugins

Ruby Bang Bang or Random Ruby Method

Ruby has a !! operator or the double bang.

!!my_method

You can double bang an existing method and instead of returning the value of the method it converts it to a boolean. It will return true if the method returns a value or false if the method returns false or nil.