Skip to content

Commit

Permalink
extract field encoding to own method
Browse files Browse the repository at this point in the history
  • Loading branch information
bmizerany committed Jan 21, 2011
1 parent 3d223cd commit b09edbe
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions lib/beefcake.rb
Expand Up @@ -84,26 +84,30 @@ def encode(buf = Buffer.new)
# TODO: Error if any required fields at nil

fields.values.sort.each do |fld|
Array(self[fld.name]).each do |val|
case fld.type
when Class # encodable
# TODO: raise error if type != val.class
buf.append_tagged_string(fld.fn, val.encode)
when Module # enum
if ! valid_enum?(fld.type, val)
raise InvalidValueError.new(fld.name, val)
end

buf.append_tagged_int32(fld.fn, val)
else
buf.__send__("append_tagged_"+fld.type.to_s, fld.fn, val)
end
end
encode!(buf, fld)
end

buf
end

def encode!(buf, fld)
Array(self[fld.name]).each do |val|
case fld.type
when Class # encodable
# TODO: raise error if type != val.class
buf.append_tagged_string(fld.fn, val.encode)
when Module # enum
if ! valid_enum?(fld.type, val)
raise InvalidValueError.new(fld.name, val)
end

buf.append_tagged_int32(fld.fn, val)
else
buf.__send__("append_tagged_"+fld.type.to_s, fld.fn, val)
end
end
end

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

0 comments on commit b09edbe

Please sign in to comment.