Class: H2o::Tags::If

Inherits:
Tag show all
Defined in:
lib/h2o/tags/if.rb

Instance Method Summary collapse

Constructor Details

#initialize(parser, argstring) ⇒ If

Returns a new instance of If.

Raises:



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/h2o/tags/if.rb', line 7

def initialize(parser, argstring)  
  raise SyntaxError, "If tag doesn't support Keywords(and or)" if argstring =~ / and|or /

  @body = parser.parse(:else, :endif)
  @else = parser.parse(:endif) if parser.token.include? 'else'
  @args = Parser.parse_arguments(argstring)
  
  # Negated condition
  first = @args.first
  if first.is_a?(Hash) && first[:operator] && [:"!", :not].include?(first[:operator])
   @negated = true
   @args.shift
  end
end

Instance Method Details

#comparision(operator, left, right) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/h2o/tags/if.rb', line 57

def comparision(operator, left, right)
  case operator
    when :> 
      left > right
    when :>=
      left >= right
    when :==
      left == right
    when :<
      left < right
    when :<=
      left <= right
    else
      false
  end
end

#evaluate(context) ⇒ Object



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/h2o/tags/if.rb', line 30

def evaluate(context)
  # Implicity evaluation
  if @args.size == 1
    object = context.resolve(@args.first)
    if object == false
      result = false
    elsif object == true
      result = true
    elsif object.respond_to? :length
      result = object.length != 0
    elsif object.respond_to? :size
      result = object.size != 0
    else
      result = !object.nil?
    end
  # Comparisons
  elsif @args.size == 3
    left, op, right = @args
    right = context.resolve(right)
    left = context.resolve(left)
    
    result = comparision(op[:operator], left, right)
  end

  return @negated ? !result : result
end

#render(context, stream) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/h2o/tags/if.rb', line 22

def render(context, stream)
  if self.evaluate(context)
    @body.render(context, stream)
  else
    @else.render(context, stream) if @else
  end
end