2

次の形式をとる複数の BinData レコードがある場合、いくつかの例を次に示します。

class DebugInfo < BinData::Record
    endian :little

    int32 :num
    array :data, :type => :debug_log, initial_length: :num
end

class GoalInfo < BinData::Record
    endian :little

    int32 :num
    array :data, :type => :goal, initial_length: :num
end

class PackageInfo < BinData::Record
    endian :little

    int32 :num
    array :data, :type => :package, initial_length: :num
end

これらはすべて基本的に同じで、異なるタイプのオブジェクトを使用して配列を作成するだけです。これらのいずれかを作成し、何らかの形でオブジェクトのタイプを配列に読み込む方法はありますか?

4

2 に答える 2

0

BinData::Base.read最初の引数 (IO オブジェクト) を除くすべてを に直接渡す#initializeので、次のようなものがうまくいくと思います。

class InfoRecord < BinData::Record
  endian :little

  int32 :num
  array :data, type: :array_type, initial_length: :num

  attr_reader :array_type

  def initialize(*args)
    @array_type = args.pop
    super
  end
end

InfoRecord.read(io, :debug_log)

ただし、これは DSL ( info_record :my_record, ...) ではうまく機能しません。

それを改善するには、代わりにこれを行うことができると思います:

class InfoRecord < BinData::Record
  # ...
  array :data, type: :array_type, initial_length: :num

  def array_type
    @params[:array_type]
  end
end

InfoRecord.read(io, array_type: :debug_log)

ハッシュ引数を処理する方法が少し複雑であるため、上記についてはあまり確信BinData::Base#initializeが持てませんが、うまくいけば、たとえば次のことができるようになります。

class MyRecord < BinData::Record
  info_record :my_info, array_type: :debug_log
end
于 2016-06-11T04:02:07.777 に答える
0
module Info
  @base_classes = {}

  def self.[](type)
    @base_classes[type] ||= Class.new(BinData::Record) {
      endian :little
      int32 :num
      array :data, :type => type, initial_length: :num
    }
  end
end

それから

class DebugInfo < Info[:debug_log]
end

class GoalInfo < Info[:goal]
end

class PackageInfo < Info[:package]
end

免責事項

未検証。

于 2016-06-11T03:47:30.767 に答える