Class: HackTree::DslContext

Inherits:
Object
  • Object
show all
Defined in:
lib/hack_tree/dsl_context.rb

Overview

Definition DSL context.

Instance Method Summary collapse

Constructor Details

#initialize(instance, parent = nil) ⇒ DslContext

Initialize self.



7
8
9
10
# File 'lib/hack_tree/dsl_context.rb', line 7

def initialize(instance, parent = nil)
  @instance, @parent = instance, parent
  @desc_parser = Parser::Desc.new
end

Instance Method Details

#desc(text) ⇒ Object



12
13
14
# File 'lib/hack_tree/dsl_context.rb', line 12

def desc(text)
  @brief_desc, @full_desc = @desc_parser[text]
end

#group(name, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/hack_tree/dsl_context.rb', line 16

def group(name, &block)
  raise "Code block expected" if not block

  name = name.to_sym

  # TODO: Check forbidden names.

  # It is allowed to reopen the groups. Find the named group.
  group = @instance.nodes.find {|r| r.name == name}

  if group
    if not group.is_a? Node::Group
      raise "Node '#{name}' already exists and it's not a group"
    end

    # It is allowed to redefine group description with another description.
    # If there is no description, the original one is retained on reopen.
    if @brief_desc
      group.brief_desc = @brief_desc
      group.full_desc = @full_desc
    end
  else
    # Create.
    group = Node::Group.new({
      :brief_desc => @brief_desc,
      :full_desc => @full_desc,
      :name => name,
      :parent => @parent,
    })

    @instance.nodes << group
  end

  # Clear last used descriptions.
  @brief_desc = @full_desc = nil

  # Create sub-context and dive into it.
  context = self.class.new(@instance, group)
  context.instance_eval(&block)
end

#hack(name, &block) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/hack_tree/dsl_context.rb', line 57

def hack(name, &block)
  raise "Code block expected" if not block

  name = name.to_sym

  # TODO: Check forbidden names.

  # It is allowed to redefine the hacks. Find the named hack.
  hack = @instance.nodes.find {|r| r.name == name}

  if hack
    if not hack.is_a? Node::Hack
      raise "Node '#{name}' already exists and it's not a hack"
    end

    # Modify hack.
    hack.brief_desc = @brief_desc
    hack.full_desc = @full_desc
    hack.block = block
  else
    # Create.
    hack = Node::Hack.new({
      :block => block,
      :brief_desc => @brief_desc,
      :full_desc => @full_desc,
      :name => name,
      :parent => @parent,
    })

    @instance.nodes << hack
  end

  # Clear last used descriptions.
  @brief_desc = @full_desc = nil

  nil
end