Class: CTypes::Enum::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/ctypes/enum/builder.rb

Overview

CTypes::Enum layout builder

This class is used to define the name/value pairs for CTypes::Enum types. The builder supports dynamic numbering similar to that used in C. The Builder is used internally by CTypes::Enum, and should not be used directly.

Examples:

Supported syntax and dynamic numbering

CTypes::Enum.new do |builder|
  # automatic numbering
  builder << :a       # :a will have value 0
  builder << :b       # :b will have value 1
  builder << {c: 10}  # :c will have value 10
  builder << :d       # :d will have value 11

  # bulk assignment
  builder << %i[e f g]  # :e == 12, :f == 11, :g == 12

  # bulk assignment with values
  builder << {z: 25, y: 24, x: 23}
  builder << :max       # :max == 26
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Builder

Returns a new instance of Builder.



29
30
31
32
33
34
# File 'lib/ctypes/enum/builder.rb', line 29

def initialize(&block)
  @map = {}
  @next = 0
  @default = nil
  block.call(self)
end

Instance Attribute Details

#defaultObject

Returns the value of attribute default.



36
37
38
# File 'lib/ctypes/enum/builder.rb', line 36

def default
  @default
end

#mapObject (readonly)

Returns the value of attribute map.



35
36
37
# File 'lib/ctypes/enum/builder.rb', line 35

def map
  @map
end

Instance Method Details

#<<(value) ⇒ Object

append new key/value pairs to the CTypes::Enum

Examples:

CTypes::Enum.new do |builder|
  # automatic numbering
  builder << :a       # :a will have value 0
  builder << :b       # :b will have value 1
  builder << {c: 10}  # :c will have value 10
  builder << :d       # :d will have value 11

  # bulk assignment
  builder << %i[e f g]  # :e == 12, :f == 11, :g == 12

  # bulk assignment with values
  builder << {z: 25, y: 24, x: 23}
  builder << :max       # :max == 26
end

Parameters:

  • value

    name or name/value pairs



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/ctypes/enum/builder.rb', line 56

def <<(value)
  case value
  when Hash
    value.each_pair { |k, v| set(k, v) }
  when ::Array
    value.each { |v| set(v, @next) }
  else
    set(value, @next)
  end
  self
end

#push(*values) ⇒ Object



68
69
70
# File 'lib/ctypes/enum/builder.rb', line 68

def push(*values)
  values.each { |v| self << v }
end