Class: Xlogin::Template

Inherits:
Object
  • Object
show all
Includes:
RelayTemplate
Defined in:
lib/xlogin/template.rb,
lib/xlogin/delegator.rb

Defined Under Namespace

Modules: RelayTemplate

Constant Summary collapse

DEFAULT_TIMEOUT =
10
DEFAULT_PROMPT =
/[$%#>] ?\z/n
RESERVED_METHODS =
i(  logout enable disable delegate )

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Template

Returns a new instance of Template.



15
16
17
18
19
20
21
# File 'lib/xlogin/template.rb', line 15

def initialize(name)
  @name    = name
  @timeout = DEFAULT_TIMEOUT
  @prompts = Array.new
  @methods = Hash.new
  @interrupt = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, &block) ⇒ Object



59
60
61
62
# File 'lib/xlogin/template.rb', line 59

def method_missing(name, *, &block)
  super unless RESERVED_METHODS.include?(name) and block_given?
  bind(name) { |*args| instance_exec(*args, &block) }
end

Instance Attribute Details

#methodsObject (readonly)

Returns the value of attribute methods.



13
14
15
# File 'lib/xlogin/template.rb', line 13

def methods
  @methods
end

#nameObject (readonly)

Returns the value of attribute name.



12
13
14
# File 'lib/xlogin/template.rb', line 12

def name
  @name
end

Instance Method Details

#bind(name = nil, &block) ⇒ Object



34
35
36
# File 'lib/xlogin/template.rb', line 34

def bind(name = nil, &block)
  @methods[name] = block
end

#build(uri, **opts) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/xlogin/template.rb', line 43

def build(uri, **opts)
  uri   = URI(uri.to_s)
  klass = Class.new(Xlogin.const_get(uri.scheme.capitalize))
  klass.class_exec(@methods) do |methods|
    methods.each do |name, block|
      if name == :enable
        define_method(name) { |*args| instance_exec([*args, opts[name]].first, &block) }
        next
      end
      define_method(name, &block)
    end
  end

  klass.new(self, uri, **opts)
end

#interrupt(&block) ⇒ Object



38
39
40
41
# File 'lib/xlogin/template.rb', line 38

def interrupt(&block)
  return @interrupt unless block
  @interrupt = block
end

#prompt(expect = nil, &block) ⇒ Object



28
29
30
31
32
# File 'lib/xlogin/template.rb', line 28

def prompt(expect = nil, &block)
  return [[DEFAULT_PROMPT, nil]] if expect.nil? && @prompts.empty?
  @prompts << [Regexp.new(expect.to_s), block] if expect
  @prompts
end

#timeout(val = nil) ⇒ Object



23
24
25
26
# File 'lib/xlogin/template.rb', line 23

def timeout(val = nil)
  @timeout = val.to_i if val
  @timeout
end