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
diff --git a/compiler/cpp/src/generate/t_rb_generator.cc b/compiler/cpp/src/generate/t_rb_generator.cc
index 6cbfeaf..5e53bcc 100644
--- a/compiler/cpp/src/generate/t_rb_generator.cc
+++ b/compiler/cpp/src/generate/t_rb_generator.cc
@@ -299,9 +299,26 @@
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 7d3f08b..607ea66 100644
--- a/test/rb/generation/test_enum.rb
+++ b/test/rb/generation/test_enum.rb
@@ -25,4 +25,10 @@
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