1

I am trying to write a script in Ruby which interactively generate some input data for a program. The idea is use QtRuby when it exists, otherwise console is used. What I tried is to

begin
  require "Qt4"
rescue LoadError => load_err
  puts "Qt not found, using console"
end

class ConsoleDefine
  # console code
end

class QtDefine < Qt::Widget
  # GUI code
end

but the interpreter refused my code when Qt4 does not exist. is there a way to deal it similar to C++, like:

#ifdef QT4
class qt4gui 
{
    // some code
};
#else
class qt4gui
{
    // dummy
};
#endif // Qt4
2
  • 1
    Source files are just source files; did you try wrapping it in something that tries to evaluate something from the package in question? Commented Feb 11, 2013 at 19:11
  • 1
    The class keyword in Ruby is just an expression (this differs from languages like Java/C# where it is a declaration). As such they can be nested in other statements/expressions: if defined? Qt; class QtDefine < Qt::Widget; ..; end; end .. now, is this "good"? Well, that's what the real answers are for :D Commented Feb 11, 2013 at 19:12

2 Answers 2

4

Use require to your advantage:

begin
  require "Qt4"
  require "my_lib/qt4"
rescue LoadError => load_err
  puts "Qt not found, using console"
  require "my_lib/console"
end

Create the two files:

# my_lib/console.rb
class ConsoleDefine
  # console code
end

# my_lib/qt4.rb
class QtDefine < Qt::Widget
  # GUI code
end
Sign up to request clarification or add additional context in comments.

Comments

1

As @pst said, you don't need a preprocessor in Ruby, since it is dynamic. So:

begin
  require "Qt4"
   class QtDefine < Qt::Widget
     # GUI code
   end
rescue LoadError => load_err
  puts "Qt not found, using console"
   class ConsoleDefine
     # console code
   end
end

2 Comments

That was my first idea, but now you have two different systems in your main file cluttered in some barely-visible rescue.
That what @xis19 wanted. In C preprocessor, the file looks the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.