Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Native::Array for array-like object wrapping
- Loading branch information
Showing
2 changed files
with
64 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -43,6 +43,67 @@ def to_n | |
end | ||
end | ||
|
||
class Array | ||
include Base | ||
include Enumerable | ||
|
||
def initialize(native, options = {}, &block) | ||
super(native) | ||
|
||
@get = options[:get] || options[:access] | ||
@set = options[:set] || options[:access] | ||
@length = options[:length] || :length | ||
@block = block | ||
|
||
if `#@native[#@length] == null` | ||
This comment has been minimized.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
meh
Author
Member
|
||
raise ArgumentError, "no length found on the array-like object" | ||
end | ||
end | ||
|
||
def each(&block) | ||
return enum_for :each unless block | ||
|
||
index = 0 | ||
length = self.length | ||
|
||
while index < length | ||
block.call(self[index]) | ||
|
||
index += 1 | ||
end | ||
|
||
self | ||
end | ||
|
||
def [](index) | ||
result = if @get | ||
`#@native[#@get](#{index})` | ||
else | ||
`#@native[#{index}]` | ||
end | ||
|
||
unless index > length | ||
if @block | ||
@block.call(result) | ||
else | ||
Native(result) | ||
end | ||
end | ||
end | ||
|
||
def []=(index, value) | ||
if @set | ||
`#@native[#@set](#{index}, #{value})` | ||
else | ||
`#@native[#{index}] = #{value}` | ||
end | ||
end | ||
|
||
def length | ||
`#@native[#@length]` | ||
end | ||
end | ||
|
||
def self.try_convert(value) | ||
%x{ | ||
if (#{native?(value)}) { | ||
|
But you have already made a function for this (
length
). Why are you not using it?