为BitStruct添加list类型

class BitStruct
  def self.list(name,element)
    module_eval <<-HERE
      rest :body
      def #{name.to_s}=(elist)
         e=Object.const_get(:#{element})
         if elist.respond_to? :each and elist.respond_to? :[] and elist[0].is_a? e
            elist.each{ |value| self.body+=value}
         elsif elist.is_a? e
            self.body=elist
         else
            raise ArgumentError,elist.to_s<<" is not a #{element}",caller
         end
      end
      def #{name.to_s}
         result=[]
         e=Object.const_get(:#{element})
         size=e.new.size
         num=self.body.size/size-1
         for i in 0..num
            result[i]=e.new(self.body[i*size,size])
         end
         result
      end
    HERE
  end
end

 

使用的话:

 

class A <BitStruct
   unsigned :id,32
end
class B<BitStruct
   list :aList,A
end
alist=[]
for i in 0..10
  a=A.new
  a.id=i
  alist.unshift a
end
b=B.new
b.aList=alist
b.aList.each{|e| puts e.id}
 

 

你可能感兴趣的:(REST)