Last Updated: February 25, 2016
·
454
· bodacious

A Simple Delegator Method for iOS Development in Rubymotion

iOS is an event-based architecture that relies heavily on the delegate pattern to send event messages from object to object.

Here's a simple module to include in your own custom classes and models to send delegate messages:

module ActsAsDelegateable

  DEFAULT_OPTIONS = { optional: false }

  def send_delegate_message(*args)
    method_name = args.shift
    options = args.last.is_a?(Hash) ? args.pop : {}
    options_with_defaults = DEFAULT_OPTIONS.merge(options)
    if options_with_defaults[:optional] 
      delegate.send(method_name, *args) if delegate && delegate.respond_to?(method_name)
    else
      delegate.send(method_name, *args)
    end
  end

end

Example use:

class MyModel

  include ActsAsDelegateable

  attr_reader :delegate

  def initialize(delegate)
    @delegate = delegate
  end

  # Methods on our model that report back to the delegate

  def something
    send_delegate_message(:did_something)
  end

  def something_optional
    send_delegate_message(:did_something_optional, optional: true)
  end

  def something_with_sender
    send_delegate_message(:did_something_with_sender, self)
  end

end

class MyController

  # Delegate callbacks defined here in the controller

  def did_something
    puts "Did something"
  end

  def did_something_with_sender(sender)
    puts "Did something with #{sender}"
  end

end

m = MyModel.new(MyController.new)
m.something
m.something_optional
m.something_with_sender