こんな感じのコードを書いて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
どうでしょ?