Search code examples
scoperubymotionteacup

Rubymotion Teacup variable scope


Following the Tweets example of Teacup, I'm trying to access a variable outside of the layout block

class WindowController < TeacupWindowController
    stylesheet :pref_window

layout do

  @loginButton = subview(
    NSButton, :loginButton,
    state: NSOffState,
    buttonType: NSSwitchButton, 
    action: 'login',
    target: self,
    )

  puts @loginButton.class

end

puts @loginButton.class

the first puts returns NSButton class, but the second one returns Nil class.

how can I access @loginButton if I need to programmatically make changes to it?

For example:

@loginButton.setState(NSOnState)

doesn't work outside the layout block.


Solution

  • You can use an attr_accessor on the WindowController, then in the layout block you can use self.loginButton and it will be assigned on the WindowController giving you access to the button.

    I'm also assuming the second puts is actually in another method and this is just example code.

    class WindowController < TeacupWindowController
      stylesheet :pref_window
      attr_accessor :loginButton
    
      layout do
    
        self.loginButton = subview(
          NSButton, :loginButton,
          state: NSOffState,
          buttonType: NSSwitchButton, 
          action: 'login',
          target: self,
        )
    
        puts self.loginButton.class
    
      end
    
      puts self.loginButton.class
    end