Is there a better way to do this in Ruby?
Python example using wxPython:
def createButtonBar(self, panel):
self.buildOneButton(panel, "FIRST", self.OnFirst)
self.buildOneButton(panel, "<< PREV", self.OnPrev, (80, 0))
self.buildOneButton(panel, "NEXT >>", self.OnNext, (160, 0))
self.buildOneButton(panel, "LAST", self.OnLast, (240, 0))
def buildOneButton(self, parent, label, handler, pos=(0,0)):
button = wx.Button(parent, -1, label, pos)
self.Bind(wx.EVT_BUTTON, handler, button)
return button
My translation to Ruby and wxRuby2:
def create_button_bar(panel)
build_one_button(panel, "FIRST", &lambda {|e|
on_first(e)})
build_one_button(panel, "<< PREV", [80, 0], &lambda {|e|
on_prev(e)})
build_one_button(panel, "NEXT >>", [160, 0], &lambda {|e|
on_next(e)})
build_one_button(panel, "LAST", [240, 0], &lambda {|e|
on_last(e)})
end
def build_one_button(parent, label, pos=[0,0], &handler)
button = Wx::Button.new(parent, -1, label, pos)
evt_button(button) {|event| yield(event)}
return button
end
> build_one_button(panel, "LAST", [240, 0], &lambda {|e|
> on_last(e)})
> def build_one_button(parent, label, pos=[0,0], &handler)
Looks like, at the very least, you could do:
build_one_button(panel, "LAST", [240,0]) {|e| on_last(e)}
I think your function is already set up to accept a block, so it's the same
syntax as each(), which you're probably already familiar with:
(1..99).each {|i| puts "#{i} bottles of beer on the wall..."}
What about passing the method name as a Symbol and then using
Object.send in the reciever? Something like:
build_one_button(panel, "FIRST", :on_first)
def build_one_button(parent, label, pos=[0,0], method_name)
button = Wx::Button.new(parent, -1, label, pos)
evt_button(button) {|event| self.send(method_name, event)}
return button
end
--
Posted via http://www.ruby-forum.com/.
I think the most direct translation of the Python code would be:
build_one_button(panel, "FIRST", method(:on_first))
Simpler than the block wrapper, IMO, and more efficient.
Lars