From 6fcaf84287d746c59f3ba126521fce3138bace12 Mon Sep 17 00:00:00 2001 From: Bryan Duxbury Date: Wed, 24 Jun 2009 17:55:53 +0000 Subject: [PATCH] THRIFT-526. rb: Generated Ruby enums have no good way to get the names back out once you have a number. enums generated in Ruby will now have a static map of enum values to names. Patch by Adam Coffman (with slight modifications). git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@788098 13f79535-47bb-0310-9956-ffa450edef68 --- compiler/cpp/src/generate/t_rb_generator.cc | 19 ++++++++++++++++++- test/rb/generation/test_enum.rb | 6 ++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/compiler/cpp/src/generate/t_rb_generator.cc b/compiler/cpp/src/generate/t_rb_generator.cc index 6cbfeaf2..5e53bcc2 100644 --- a/compiler/cpp/src/generate/t_rb_generator.cc +++ b/compiler/cpp/src/generate/t_rb_generator.cc @@ -299,9 +299,26 @@ void t_rb_generator::generate_enum(t_enum* tenum) { indent() << name << " = " << value << endl; } + //Create a hash mapping values back to their names (as strings) since ruby has no native enum type + indent(f_types_) << "VALUE_MAP = {"; + bool first = true; + value = -1; + for(c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { + //Populate the hash + //If no value is given, use the next available one + if ((*c_iter)->has_value()) + value = (*c_iter)->get_value(); + else ++value; + + first ? first = false : f_types_ << ", "; + f_types_ << value << " => \"" << capitalize((*c_iter)->get_name()) << "\""; + + } + f_types_ << "}" << endl; + // Create a set with valid values for this enum indent(f_types_) << "VALID_VALUES = Set.new(["; - bool first = true; + first = true; for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { // Populate the set first ? first = false: f_types_ << ", "; diff --git a/test/rb/generation/test_enum.rb b/test/rb/generation/test_enum.rb index 7d3f08ba..607ea66b 100644 --- a/test/rb/generation/test_enum.rb +++ b/test/rb/generation/test_enum.rb @@ -25,4 +25,10 @@ class TestEnumGeneration < Test::Unit::TestCase def test_enum_valid_values assert_equal(Numberz::VALID_VALUES, Set.new([Numberz::ONE, Numberz::TWO, Numberz::THREE, Numberz::FIVE, Numberz::SIX, Numberz::EIGHT])) end + + def test_enum_hash + Numberz::VALID_VALUES.each do |value| + assert_equal(Numberz.const_get(Numberz::VALUE_MAP[value].to_sym), value) + end + end end \ No newline at end of file -- 2.17.1