Forum: Ruby-Gnome 2 click can't run my class

Posted by Pen Ttt (luofeiyu)
on 2010-07-07 05:08
there is simple class,it can run,i have tested it
  class  Myfile
   def  self.openit(myfile)
  file=open(myfile,'r')
  while line=file.gets
   puts  line
   end
  file.close
  end
  end
 Myfile.openit("/home/pt/code")

when i add it into  gtk ,it can't work.
here is my program:
require 'gtk2'
button = Gtk::Button.new("my ruby")
button.signal_connect("clicked") {
   Myfile.openit("/home/pt/code")
}
window = Gtk::Window.new
window.signal_connect("delete_event") {
  puts "delete event occurred"
  false
}
window.signal_connect("destroy") {
  puts "destroy event occurred"
  Gtk.main_quit
}
window.border_width = 10
window.add(button)
window.show_all
Gtk.main

  class  Myfile
    def  self.openit(myfile)
      file=open(myfile,'r')
      while line=file.gets
        puts  line
      end
    file.close
    end
  end

the outout  is:

pt@pt-laptop:~$ ruby  /home/pt/t10.rb
/home/pt/t10.rb:4: uninitialized constant Myfile
   from /home/pt/t10.rb:27:in `call'
   from /home/pt/t10.rb:27:in `main'
   from /home/pt/t10.rb:27
how to revise it?
Posted by Geoff Youngs (Guest)
on 2010-07-07 10:39
(Received via mailing list)
Ruby code is executed as it is reached - and class definitions are ruby
code.

Your code is laid out in the form:

<gtk program>
<class definition>

which means that the class 'Myfile' doesn't get defined until the 
program
has finished running.


To fix it, you'll need to move the Myfile class to the top of the file 
so
that the class gets defined before you try to use it.

HTH,


G.
Posted by Pen Ttt (luofeiyu)
on 2010-07-07 14:58
i fixed it,it can run now.think you
    class  Myfile
    def  self.openit(myfile)
      file=open(myfile,'r')
      while line=file.gets
      puts  line
    end
    file.close
    end
   end
require 'gtk2'
button = Gtk::Button.new("my ruby")
button.signal_connect("clicked") {
 Myfile.openit("/home/pt/code")
}
window = Gtk::Window.new
window.signal_connect("delete_event") {
  puts "delete event occurred"
  false
}
window.signal_connect("destroy") {
  puts "destroy event occurred"
  Gtk.main_quit
}
window.border_width = 10
window.add(button)
window.show_all
Gtk.main
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.