Ruby GTK Blocks

As I was exploring gtk in ruby I found myself frustrated with the inability to create nested widgets in equally nested code. Such as:


$main = Gtk::Window.new
$main << Gtk::HBox.new do |b|
b << Gtk::Button.new(“click me”)
b << Gtk::VBox.new do |v|
… etc etc
end
end

No problem, eigenclasses to the rescue! I just add this simple thing (to a lib or just the beginning of my file):


class << Gtk::Widget
def new *args, &block
x = super
yield x if block
x
end
end

That’s all, now you can use good ol’ ruby blocks to make GUI programming less obscene.

07 Nov 01:51
Tags: programming, annoyances, ruby
Very cool. And elegant. Just a note, though, that libglade is really the idea way to create tons of widgets with only one line of code. Once you get used to it, libglade is really a better way to construct widgets.
15 Feb 22:04 by … Michael Torrie torriem at chem dot byu dot edu

Post a comment

Website and email are optional. Email will be displayed user at example dot com.