Class: Ruckus::Choice

Inherits:
Parsel show all
Defined in:
lib/ruckus/choice.rb

Overview

A choice wraps a blob, and, on input, picks what to put in the blob based on a code block. Use choices to dispatch protocol responses based on type codes, etc.

Direct Known Subclasses

Dictionary

Constant Summary

Constants inherited from Parsel

Parsel::VERBOTEN

Instance Attribute Summary

Attributes inherited from Parsel

#name, #parent, #rendered_offset, #rendering, #tag, #value

Instance Method Summary collapse

Methods inherited from Parsel

bytes_for_bits, coerce, #each_matching_selector, endian?, factory?, #find_containing, #find_tag, #find_tag_struct, #fixup, #in, #incomplete!, #index_for_selectors, #inspect, #matches_selector?, #method_missing, #native?, native?, #next, #out, #parent_structure, #permute, #prev, #resolve, #respond_to?, #root, #size, #visit, #where_am_i?

Constructor Details

#initialize(opts = {}, &block) ⇒ Choice

You must call Choice.new with a block that takes two arguments — an input string and a reference to the choice instance. For instance:

data << Choice.new do |buf, this|
         if this.parent_struct.message_code == Codes::ERROR
             this << ErrorFrame.new
         else
             this << ResponseFrame.new
         end
         this[-1].capture(buf)
     end


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ruckus/choice.rb', line 24

def initialize(opts={}, &block)
    @parent = opts[:parent]
    raise "provide a block" if not block_given? and not opts[:block] and not respond_to? :choose
    if not opts[:block] and not block_given?
        opts[:block] = lambda {|x, y| self.choose(x)}
    end
    super(opts)
    @block ||= block
    @value = Blob.new
    @value.parent = self
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Ruckus::Parsel

Instance Method Details

#<<(o) ⇒ Object



49
50
51
52
# File 'lib/ruckus/choice.rb', line 49

def <<(o)
    @value << o
    o.parent = self
end

#capture(str) ⇒ Object

Call the block, which must return the remainder string.



45
46
47
# File 'lib/ruckus/choice.rb', line 45

def capture(str)
    block.call(str, self)
end

#to_s(off = nil) ⇒ Object

Just render the blob



38
39
40
41
# File 'lib/ruckus/choice.rb', line 38

def to_s(off=nil)
    @rendered_offset = off || 0
    (@value)? @value.to_s(off) : ""
end