From 681bf1fc481883293a47def022267577224e53b8 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 8 Aug 2011 19:48:12 -0700 Subject: backporting IO#binread for 1.8 users --- activesupport/lib/active_support/core_ext/io.rb | 15 +++++++++++++++ activesupport/test/core_ext/io_test.rb | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 activesupport/lib/active_support/core_ext/io.rb create mode 100644 activesupport/test/core_ext/io_test.rb diff --git a/activesupport/lib/active_support/core_ext/io.rb b/activesupport/lib/active_support/core_ext/io.rb new file mode 100644 index 0000000000..75f1055191 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/io.rb @@ -0,0 +1,15 @@ +if RUBY_VERSION < '1.9.2' + +# :stopdoc: +class IO + def self.binread(name, length = nil, offset = nil) + return File.read name unless length || offset + File.open(name, 'rb') { |f| + f.seek offset if offset + f.read length + } + end +end +# :startdoc: + +end diff --git a/activesupport/test/core_ext/io_test.rb b/activesupport/test/core_ext/io_test.rb new file mode 100644 index 0000000000..b9abf685da --- /dev/null +++ b/activesupport/test/core_ext/io_test.rb @@ -0,0 +1,23 @@ +require 'abstract_unit' + +require 'active_support/core_ext/io' + +class IOTest < Test::Unit::TestCase + def test_binread_one_arg + assert_equal File.read(__FILE__), IO.binread(__FILE__) + end + + def test_binread_two_args + assert_equal File.read(__FILE__).bytes.first(10).pack('C*'), + IO.binread(__FILE__, 10) + end + + def test_binread_three_args + actual = IO.binread(__FILE__, 5, 10) + expected = File.open(__FILE__, 'rb') { |f| + f.seek 10 + f.read 5 + } + assert_equal expected, actual + end +end -- cgit v1.2.3