Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions mrbgems/mruby-exit/mrblib/mruby_exit.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,50 @@
class SystemExit
##
# call-seq:
# SystemExit.new(status = true, message = "SystemExit") -> system_exit
# SystemExit.new(message) -> system_exit
#
# Creates a SystemExit with the exit status given, `true` and `false`
# meaning success and failure. Without a status, it stands for success.
#
# SystemExit.new.status #=> 0
# SystemExit.new(false).status #=> 1
# SystemExit.new(3, "bye").status #=> 3
#
def initialize(*args)
raise ArgumentError, "wrong number of arguments (given #{args.size}, expected 0..2)" if args.size > 2
status = args[0]
if status == true
@status = 0
elsif status == false
@status = 1
elsif status.is_a?(Integer)
@status = status
else
raise ArgumentError, "wrong number of arguments (given 2, expected 0..1)" if args.size == 2
@status = 0
return super
end
args.size == 2 ? super(args[1]) : super()
end

##
# call-seq:
# system_exit.status -> integer
#
# The exit status.
#
def status
@status
end

##
# call-seq:
# system_exit.success? -> true or false
#
# Whether the exit status means success: it is 0.
#
def success?
@status == 0
end
end
34 changes: 34 additions & 0 deletions mrbgems/mruby-exit/test/exit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,37 @@
assert_raise(RangeError) { exit(big) }
assert_raise(RangeError) { exit(-big) }
end

assert('SystemExit.new') do
e = SystemExit.new
assert_equal 0, e.status
assert_equal "SystemExit", e.message
assert_equal 1, SystemExit.new(false).status
assert_equal 0, SystemExit.new(true).status
e = SystemExit.new(3, "bye")
assert_equal 3, e.status
assert_equal "bye", e.message
e = SystemExit.new("bye")
assert_equal 0, e.status
assert_equal "bye", e.message
assert_raise(ArgumentError) { SystemExit.new("a", "b") }
assert_raise(ArgumentError) { SystemExit.new(1, "b", 3) }
end

assert('SystemExit#success?') do
assert_true SystemExit.new.success?
assert_true SystemExit.new(0).success?
assert_false SystemExit.new(false).success?
assert_false SystemExit.new(2).success?
begin
exit(2)
rescue SystemExit => e
assert_equal 2, e.status
assert_false e.success?
end
begin
exit
rescue SystemExit => e
assert_true e.success?
end
end
Loading