Skip to content

Commit

Permalink
inspect shows name of const for enums
Browse files Browse the repository at this point in the history
  • Loading branch information
bmizerany committed Feb 15, 2011
1 parent cff0330 commit 16f50f9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
25 changes: 23 additions & 2 deletions lib/beefcake.rb
Expand Up @@ -104,7 +104,16 @@ def encode!(buf, fld, fn)
end

def valid_enum?(mod, val)
mod.constants.any? {|name| mod.const_get(name) == val }
!!name_for(mod, val)
end

def name_for(mod, val)
mod.constants.each do |name|
if mod.const_get(name) == val
return name
end
end
nil
end

def validate!
Expand Down Expand Up @@ -204,7 +213,19 @@ def ==(o)

def inspect
set = fields.values.select {|fld| self[fld.name] != nil }
flds = set.map {|fld| "#{fld.name}: #{self[fld.name].inspect}" }

flds = set.map do |fld|
val = self[fld.name]

case fld.type
when Module
title = name_for(fld.type, val) || "-NA-"
"#{fld.name}: #{title}(#{val.inspect})"
else
"#{fld.name}: #{val.inspect}"
end
end

"<#{self.class.name} #{flds.join(", ")}>"
end

Expand Down
7 changes: 7 additions & 0 deletions test/message_test.rb
Expand Up @@ -318,4 +318,11 @@ def test_inspect
assert_equal "<SimpleMessage b: \"testing\">", msg.inspect
end

def test_inspect_enums
msg = EnumsMessage.new :a => 1
assert_equal "<EnumsMessage a: A(1)>", msg.inspect
msg.a = 2
assert_equal "<EnumsMessage a: -NA-(2)>", msg.inspect
end

end

0 comments on commit 16f50f9

Please sign in to comment.