LoginSignup
11
11

More than 5 years have passed since last update.

RubyMotionでSingleton

Last updated at Posted at 2013-06-06

こんな感じのコードを書いてSingletonにしたいクラスでinclude

module SingletonClass
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def new
      super
      instance
    end

    def instance
      Dispatch.once { @instance ||= alloc.init }
      @instance
    end
  end
end

Executes a block object once and only once for the lifetime of an application.

Dispatch.onceにブロックで渡した処理は、アプリのライフサイクル中一回しか実行されないらしrい

これを使うと、クライアントのControllerをinteractive debuggerでデバッグする時便利です。
以下は、ProMotionというgemを独自に拡張したコードで、self.viewにUIWebViewが入ってます。

class GithubScreen < ProMotion::WebViewScreen
  include SingletonClass

  def on_load
    open_url 'http://github.com'
  end

end

シングルトンなので、以下のようにrake実行してシミュレーター起動させてから、
Controller部分のインスタンスが、シミュレーター上に表示されているものと共有できるので、
以下のように実行するとWebViewのリロードができます。

$ rake
....
> g = GithubScreen.new
> g.view.reload

どうでしょ?

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11