Class: XDR::Struct

Inherits:
Object
  • Object
show all
Extended by:
Concerns::ConvertsToXDR, DSL::Struct
Includes:
ActiveModel::AttributeMethods, ActiveModel::Model
Defined in:
lib/xdr/struct.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Concerns::ConvertsToXDR

from_xdr, read, valid?, write

Methods included from DSL::Struct

attribute

Constructor Details

#initialize(attributes = {}) ⇒ Struct

Returns a new instance of Struct.



39
40
41
42
# File 'lib/xdr/struct.rb', line 39

def initialize(attributes = {})
  @attributes = {}
  super
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



18
19
20
# File 'lib/xdr/struct.rb', line 18

def attributes
  @attributes
end

Class Method Details

.read(io) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/xdr/struct.rb', line 20

def self.read(io)
  new.tap do |result|
    fields.each do |name, type|
      result.public_send("#{name}=", type.read(io))
    end
  end
end

.valid?(val) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/xdr/struct.rb', line 35

def self.valid?(val)
  val.is_a?(self)
end

.write(val, io) ⇒ Object



28
29
30
31
32
33
# File 'lib/xdr/struct.rb', line 28

def self.write(val, io)
  fields.each do |name, type|
    field_val = val.public_send(name)
    type.write(field_val, io)
  end
end

Instance Method Details

#==(other) ⇒ Object

Compares two structs for equality



65
66
67
68
# File 'lib/xdr/struct.rb', line 65

def ==(other)
  return false unless other.is_a?(self.class)
  other.attributes == attributes
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


70
71
72
73
# File 'lib/xdr/struct.rb', line 70

def eql?(other)
  return false unless other.is_a?(self.class)
  other.attributes.eql? attributes
end

#hashObject



75
76
77
# File 'lib/xdr/struct.rb', line 75

def hash
  [self.class, attributes].hash
end

#read_attribute(attr) ⇒ Object



79
80
81
# File 'lib/xdr/struct.rb', line 79

def read_attribute(attr)
  @attributes[attr]
end

#to_xdr(format = :raw) ⇒ String

Serializes struct to xdr, return a string of bytes

Parameters:

  • format (:raw, :hex, :base64) (defaults to: :raw)

    The encoding used for the bytes produces, one of (:raw, :hex, :base64)

Returns:

  • (String)

    The encoded bytes of this struct



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/xdr/struct.rb', line 50

def to_xdr(format = :raw)
  raw = self.class.to_xdr(self)

  case format
  when :raw then raw
  when :hex then raw.unpack1("H*")
  when :base64 then Base64.strict_encode64(raw)
  else
    raise ArgumentError, "Invalid format #{format.inspect}; must be :raw, :hex, or :base64"
  end
end

#write_attribute(attr, value) ⇒ Object



83
84
85
# File 'lib/xdr/struct.rb', line 83

def write_attribute(attr, value)
  @attributes[attr] = value
end