Last active
May 29, 2016 23:07
-
-
Save nativestranger/f06f33f01be6af5fe0df627f5d51d5cd to your computer and use it in GitHub Desktop.
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
source 'https://rubygems.org' | |
gem 'rspec', group: :test | |
ruby "2.3.0" |
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
module MyFlatten | |
def self.included(base) | |
if base.ancestors.include?(Array) | |
base.class_eval { | |
def my_flatten | |
result = [] | |
self.each do |object| | |
object_has_my_flatten = object.class.ancestors.include?(MyFlatten) && object.respond_to?(:my_flatten) | |
object_has_my_flatten ? result += object.my_flatten : result << object | |
end | |
result | |
end | |
} | |
else | |
raise Exception.new('MyFlatten included in non-Array class.') | |
end | |
end | |
end |
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
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __FILE__) | |
Bundler.require(:test) | |
$LOAD_PATH.unshift '.' | |
require 'my_flatten' | |
describe MyFlatten do | |
it "defines #my_flatten without exception when included into Array or an Array subclass" do | |
class MyArray < Array; end | |
expect(Array.include(MyFlatten)).to be_truthy | |
expect(MyArray.include(MyFlatten)).to be_truthy | |
expect(Array.new.respond_to?(:my_flatten)).to be_truthy | |
expect(MyArray.new.respond_to?(:my_flatten)).to be_truthy | |
end | |
it "raises an excetion & doesn't define #my_flatten when included into a non Array class" do | |
expect { String.include(MyFlatten) }.to raise_error('MyFlatten included in non-Array class.') | |
expect(String.new.respond_to?(:my_flatten)).to be_falsy | |
end | |
it "defines #my_flatten to behave like array#flatten" do | |
arrays = [ [], [1,2,3], [[1,2,[3]],4], [nil, {}, '', [[1]]] ] | |
arrays.each { |array| expect(array.my_flatten).to eq(array.flatten) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment