summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--ext/ruby2d/ruby2d.c20
-rw-r--r--lib/ruby2d/exceptions.rb9
-rw-r--r--lib/ruby2d/image.rb11
-rw-r--r--test/image_spec.rb11
4 files changed, 36 insertions, 15 deletions
diff --git a/ext/ruby2d/ruby2d.c b/ext/ruby2d/ruby2d.c
index 6c3dc4e..d91e0dc 100644
--- a/ext/ruby2d/ruby2d.c
+++ b/ext/ruby2d/ruby2d.c
@@ -148,6 +148,18 @@ static void free_window() {
/*
+ * File#exists? for MRuby
+ */
+#if MRUBY
+static R_VAL file_exists(mrb_state* mrb, R_VAL self) {
+ mrb_value path;
+ mrb_get_args(mrb, "o", &path);
+ return S2D_FileExists(RSTRING_PTR(path)) ? R_TRUE : R_FALSE;
+}
+#endif
+
+
+/*
* Ruby2D::Image#init
* Initialize image structure data
*/
@@ -793,6 +805,11 @@ int main(void) {
// Load the Ruby 2D library
mrb_load_irep(mrb, ruby2d_lib);
+
+ // Add missing MRuby classes, methods
+ R_CLASS file_class = mrb_define_class(mrb, "File", mrb->object_class);
+ mrb_define_class_method(mrb, file_class, "exists?", file_exists, r_args_req(1));
+
#else
/*
* Ruby C extension init
@@ -867,6 +884,9 @@ void Init_ruby2d() {
// Load the Ruby 2D app
mrb_load_irep(mrb, ruby2d_app);
+ // If an exception, print error
+ if (mrb->exc) mrb_print_error(mrb);
+
// Close the MRuby environment
mrb_close(mrb);
#endif
diff --git a/lib/ruby2d/exceptions.rb b/lib/ruby2d/exceptions.rb
index 84880e1..687ab11 100644
--- a/lib/ruby2d/exceptions.rb
+++ b/lib/ruby2d/exceptions.rb
@@ -2,14 +2,5 @@
module Ruby2D
class Error < StandardError
- def colorize(msg, c); "\e[#{c}m#{msg}\e[0m" end
- def error(msg); colorize(msg, '4;31') end
- def bold(msg); colorize(msg, '1') end
-
- def initialize(msg)
- super(msg)
- puts error("\nRuby 2D Error:") << " #{msg}" <<
- bold("\nOccurred in:\n #{caller.last}\n")
- end
end
end
diff --git a/lib/ruby2d/image.rb b/lib/ruby2d/image.rb
index 7938bea..587a3c0 100644
--- a/lib/ruby2d/image.rb
+++ b/lib/ruby2d/image.rb
@@ -9,12 +9,11 @@ module Ruby2D
def initialize(x, y, path)
- # TODO: Check if file exists
- # `File.exists?` is not available in MRuby
- # Ideally would do:
- # unless File.exists? path
- # raise Error, "Cannot find image file `#{path}`"
- # end
+ unless RUBY_ENGINE == 'opal'
+ unless File.exists? path
+ raise Error, "Cannot find image file `#{path}`"
+ end
+ end
@type_id = 3
@x, @y, @path = x, y, path
diff --git a/test/image_spec.rb b/test/image_spec.rb
new file mode 100644
index 0000000..43950c9
--- /dev/null
+++ b/test/image_spec.rb
@@ -0,0 +1,11 @@
+require 'ruby2d'
+
+RSpec.describe Ruby2D::Image do
+
+ describe '#new' do
+ it "raises exception if image file doesn't exist" do
+ expect { Image.new(0, 0, 'bad_image.png') }.to raise_error(Ruby2D::Error)
+ end
+ end
+
+end