forked from jruby/jruby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtype.rb
More file actions
36 lines (31 loc) · 973 Bytes
/
Copy pathtype.rb
File metadata and controls
36 lines (31 loc) · 973 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module JRuby
module Type
# Helper method to coerce a value into a specific class.
# Raises a TypeError if the coercion fails or the returned value
# is not of the right class.
# (from Rubinius)
def self.coerce_to(obj, cls, meth)
return obj if obj.kind_of?(cls)
begin
ret = obj.__send__(meth)
rescue Exception => e
raise TypeError, "Coercion error: #{obj.inspect}.#{meth} => #{cls} failed:\n" \
"(#{e.message})"
end
raise TypeError, "Coercion error: obj.#{meth} did NOT return a #{cls} (was #{ret.class})" unless ret.kind_of? cls
ret
end
def self.coerce_to_int(obj)
coerce_to(obj, Integer, :to_int)
end
def self.coerce_to_ary(obj)
coerce_to(obj, Array, :to_ary)
end
def self.coerce_to_str(obj)
coerce_to(obj, String, :to_str)
end
def self.is_array?(obj)
coerce_to(obj, Array, :to_ary) if obj.respond_to? :to_ary
end
end
end