Nathan Weizenbaum was helping me with a few issues in a pet project I’m working on.
In the process, I ended up learning a really neat trick that Ruby can do.
To give you a bit of background, I’m working on a GTK Tray Icon. To make a menu spawn upon right-clicking the tray icon, you’d expect to see something like this:
require 'gtk2'
class TrayIcon
def initialize
trayicon = Gtk::StatusIcon.new
trayicon.set_icon_name('folder')
trayicon.set_tooltip('My Tray Icon')
trayicon.signal_connect('popup-menu') { |button, activate_time| on_right_click(button, activate_time) }
end
def on_right_click(status_icon, button, activate_time)
rc_menu = Gtk::Menu.new
exit = Gtk::ImageMenuItem.new('Quit')
exit_image = Gtk::Image.new(Gtk::Stock::QUIT, Gtk::IconSize::MENU)
exit.set_image(exit_image)
exit.signal_connect('activate') { Gtk.main_quit }
rc_menu.append(exit)
rc_menu.show_all
rc_menu.popup(nil, nil, button, activate_time)
end
end
But, the line 8th line (trayicon.signal_connect …) is a bit unwieldy. The thing is, we need those arguments to be passed for everything to work. And that’s where Ruby’s Proc handling comes in to save me. The same line can be re-written, and work, using the following line instead:
trayicon.signal_connect('popup-menu', &method(:on_right_click))
0 Responses to “The Little Things in Life Rock”