From 8f6ce1a17ea1d73c3becc16ece79046e113daf8e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 13 Nov 2012 11:11:11 -0800 Subject: backporting Struct#to_h from ruby 2.0 --- activesupport/lib/active_support/core_ext/struct.rb | 6 ++++++ activesupport/test/core_ext/struct_test.rb | 10 ++++++++++ 2 files changed, 16 insertions(+) create mode 100644 activesupport/lib/active_support/core_ext/struct.rb create mode 100644 activesupport/test/core_ext/struct_test.rb diff --git a/activesupport/lib/active_support/core_ext/struct.rb b/activesupport/lib/active_support/core_ext/struct.rb new file mode 100644 index 0000000000..c2c30044f2 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/struct.rb @@ -0,0 +1,6 @@ +# Backport of Struct#to_h from Ruby 2.0 +class Struct # :nodoc: + def to_h + Hash[members.zip(values)] + end +end unless Struct.instance_methods.include?(:to_h) diff --git a/activesupport/test/core_ext/struct_test.rb b/activesupport/test/core_ext/struct_test.rb new file mode 100644 index 0000000000..0dff7b32d2 --- /dev/null +++ b/activesupport/test/core_ext/struct_test.rb @@ -0,0 +1,10 @@ +require 'abstract_unit' +require 'active_support/core_ext/struct' + +class StructExt < ActiveSupport::TestCase + def test_to_h + x = Struct.new(:foo, :bar) + z = x.new(1, 2) + assert_equal({ foo: 1, bar: 2 }, z.to_h) + end +end -- cgit v1.2.3