class Beowulf::Type::Extension

Public Class Methods

new(options = {}) click to toggle source
# File lib/beowulf/type/extension.rb, line 10
def initialize(options = {})
  opt = options.dup
  @type = opt.delete(:type)

  opt.each do |k, v|
    instance_variable_set("@#{k}", type(@type, k, v))
  end

  unless Extension::known_extension_names.include? @type
    raise ExtensionError, "Unsupported extension type: #{@type}"
  end
end

Private Class Methods

known_extension_names() click to toggle source
# File lib/beowulf/type/extension.rb, line 86
def self.known_extension_names
  list_extensions.map { |ex| ex["extension"].to_sym }
end
list_extensions() click to toggle source
# File lib/beowulf/type/extension.rb, line 74
def self.list_extensions
  data_exts = '[
    {
      "extension": "extension_json_type",
      "params": [
        "value"
      ]
    }
  ]'
  @list_extensions = JSON.parse(data_exts)
end
param_names(type) click to toggle source
# File lib/beowulf/type/extension.rb, line 90
def self.param_names(type)
  list_extensions.each do |ex|
    if ex['extension'].to_sym == type.to_sym
      return ex['params'].map(&:to_sym)
    end
  end
end

Public Instance Methods

payload() click to toggle source
# File lib/beowulf/type/extension.rb, line 51
def payload
  params = {}
  params["type"] = @type.to_s
  Extension::param_names(@type.to_sym).each do |p|
    next unless defined? p
    # puts p
    v = instance_variable_get("@#{p}")
    # puts v
    next if v.nil?
    next if v.class == Beowulf::Type::Future

    params[p] = case v
                when Beowulf::Type::ExtensionJson
                  v.to_s
                else; v
                end
  end

  params
end
to_bytes() click to toggle source
# File lib/beowulf/type/extension.rb, line 23
def to_bytes
  bytes = [id(@type.to_sym)].pack('C')

  Extension::param_names(@type.to_sym).each do |p|
    next unless defined? p
    # puts p
    v = instance_variable_get("@#{p}")
    # puts v
    bytes += v.to_bytes and next if v.respond_to? :to_bytes

    bytes += case v
             when Symbol then pakStr(v.to_s)
             when String then pakStr(v)
             when Integer then paks(v)
             when TrueClass then pakC(1)
             when FalseClass then pakC(0)
             when ::Array then pakArr(v)
             when ::Hash then pakHash(v)
             when ExtensionJson then v.to_bytes
             when NilClass then next
             else
               raise ExtensionError, "Unsupported type: #{v.class}"
             end
  end

  bytes
end