Class: SyntaxTree::Case

Inherits:
Node
  • Object
show all
Defined in:
lib/syntax_tree/node.rb

Overview

Case represents the beginning of a case chain.

case value
when 1
  "one"
when 2
  "two"
else
  "number"
end

Instance Attribute Summary collapse

Attributes inherited from Node

#location

Instance Method Summary collapse

Constructor Details

#initialize(keyword:, value:, consequent:, location:, comments: []) ⇒ Case

Returns a new instance of Case.



2770
2771
2772
2773
2774
2775
2776
# File 'lib/syntax_tree/node.rb', line 2770

def initialize(keyword:, value:, consequent:, location:, comments: [])
  @keyword = keyword
  @value = value
  @consequent = consequent
  @location = location
  @comments = comments
end

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



2768
2769
2770
# File 'lib/syntax_tree/node.rb', line 2768

def comments
  @comments
end

#consequentObject (readonly)

In | When

the next clause in the chain



2765
2766
2767
# File 'lib/syntax_tree/node.rb', line 2765

def consequent
  @consequent
end

#keywordObject (readonly)

Kw

the keyword that opens this expression



2759
2760
2761
# File 'lib/syntax_tree/node.rb', line 2759

def keyword
  @keyword
end

#valueObject (readonly)

nil | untyped

optional value being switched on



2762
2763
2764
# File 'lib/syntax_tree/node.rb', line 2762

def value
  @value
end

Instance Method Details

#child_nodesObject Also known as: deconstruct



2778
2779
2780
# File 'lib/syntax_tree/node.rb', line 2778

def child_nodes
  [keyword, value, consequent]
end

#deconstruct_keys(keys) ⇒ Object



2784
2785
2786
2787
2788
2789
2790
2791
2792
# File 'lib/syntax_tree/node.rb', line 2784

def deconstruct_keys(keys)
  {
    keyword: keyword,
    value: value,
    consequent: consequent,
    location: location,
    comments: comments
  }
end

#format(q) ⇒ Object



2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
# File 'lib/syntax_tree/node.rb', line 2794

def format(q)
  q.group do
    q.format(keyword)

    if value
      q.text(" ")
      q.format(value)
    end

    q.breakable(force: true)
    q.format(consequent)
    q.breakable(force: true)

    q.text("end")
  end
end

#pretty_print(q) ⇒ Object



2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
# File 'lib/syntax_tree/node.rb', line 2811

def pretty_print(q)
  q.group(2, "(", ")") do
    q.text("case")

    q.breakable
    q.pp(keyword)

    if value
      q.breakable
      q.pp(value)
    end

    q.breakable
    q.pp(consequent)

    q.pp(Comment::List.new(comments))
  end
end

#to_json(*opts) ⇒ Object



2830
2831
2832
2833
2834
2835
2836
2837
2838
# File 'lib/syntax_tree/node.rb', line 2830

def to_json(*opts)
  {
    type: :case,
    value: value,
    cons: consequent,
    loc: location,
    cmts: comments
  }.to_json(*opts)
end