Class: Ruty::Tags::If

Inherits:
Ruty::Tag show all
Defined in:
lib/ruty/tags/conditional.rb

Overview

Ruty Conditional Tags

Author

Armin Ronacher

Copyright © 2006 by Armin Ronacher

You can redistribute it and/or modify it under the terms of the BSD license.

Instance Method Summary collapse

Constructor Details

#initialize(parser, argstring) ⇒ If

Returns a new instance of If.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ruty/tags/conditional.rb', line 11

def initialize parser, argstring
  # parse everything until the next else or endif tag
  # and save in a variable if it was a else tag for
  # postprocessing.
  was_else = false
  @body = parser.parse_until do |name, a|
    if [:endif, :else].include? name
      was_else = name == :else
      true
    end
  end

  args = parser.parse_arguments(argstring)
  @else_body = parser.parse_until { |name, a| name == :endif } if was_else

  if not [1, 2].include?(args.length) or \
     (args.length == 2 and args[0] != :not)
    parser.fail('invalid syntax for if tag')
  end

  @negated = args.length == 2
  @item = @negated ? args[1] : args[0]
end

Instance Method Details

#render_node(context, stream) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/ruty/tags/conditional.rb', line 35

def render_node context, stream
  item = context.resolve(@item)
  if item == false
    val = false
  elsif item.respond_to?(:nonzero?)
    val = item.nonzero?
  elsif item.respond_to?(:empty?)
    val = !item.empty?
  elsif item.respond_to?(:size)
    val = item.size > 0
  elsif item.respond_to?(:length)
    val = item.length > 0
  else
    val = !item.nil?
  end
  if @negated ? !val : val
    @body.render_node(context, stream)
  elsif @else_body
    @else_body.render_node(context, stream)
  end
end