その他
    ホーム技術発信DoRubyRubyCocoaでウィンドウとボタンを表示する

    RubyCocoaでウィンドウとボタンを表示する

    この記事はアピリッツの技術ブログ「DoRuby」から移行した記事です。情報が古い可能性がありますのでご注意ください。

    こんにちは。

    KBMJの佐藤です。

    今回はRubyCocoaについて紹介します。

    RubyCocoaとは、RubyでCocoaアプリケーションを書いたりできるようになるラ

    イブラリおよびフレームワークです。

    RubyCocoaのインストール

    以下のURLからdmgをダウンロードして、インストールします。

    http://sourceforge.net/project/showfiles.php?group_id=44114

    LeopardにはOSに標準搭載されているので、インストールの必要はありません。

    コードを書く

    HelloWorld.rb というファイル名でコードを書きます。

    require 'osx/cocoa'
    include OSX
    
    class AppDelegate <  NSObject
       def sayHello(sender)
         puts "Hello again, World!"
       end
    end
    
    
    if $0 == __FILE__ then
      app = NSApplication.sharedApplication()
    
      app.setDelegate(AppDelegate.alloc.init)
    
      frame = [200.0, 300.0, 250.0, 100.0]
      win = NSWindow.alloc.initWithContentRect_styleMask_backing_defer(frame, 15, 2, 0)
      win.setTitle 'HelloWorld'
      win.setLevel(3)                       # floating window
    
      hel = NSButton.alloc.initWithFrame [10.0, 10.0, 80.0, 80.0]
      win.contentView.addSubview(hel)
      hel.setBezelStyle(4)
      hel.setTitle( 'Hello!' )
      hel.setTarget( app.delegate )
      hel.setAction( "sayHello:" )
    
      bye = NSButton.alloc.initWithFrame [100.0, 10.0, 80.0, 80.0]
      win.contentView.addSubview(bye)
      bye.setBezelStyle( 4 )
      bye.setTarget(app)
      bye.setAction('stop:')
      bye.setEnabled( true )
      bye.setTitle( 'Goodbye!' )
    
      win.display()
      win.orderFrontRegardless()            ## but this one does
    
      app.run()
    end
    

    実行する

    ターミナルで

    ruby HelloWorld.rb

    と打ち込むと、以下のようなウィンドウが表示されます。

    http://farm4.static.flickr.com/3185/2928545086_c4406c295c.jpg

    Hello! ボタンを押すと、ターミナルにメッセージが表示されます。

    http://farm4.static.flickr.com/3263/2927675663_c6011ef314.jpg

    Goodbye! ボタンを押すと、ウィンドウが閉じます。

    さいごに

    RubyCocoaを使えば、CoreAnimationなど、MacOSXのエレガントなフレームワー

    クを手軽に試してみることが出来ます。

    皆さんもぜひ試してみて下さい。

    個人ブログ

    拡張現実ライフ