Class: Liquid::Cycle

Inherits:
Tag
  • Object
show all
Defined in:
lib/liquid/tags/cycle.rb

Defined Under Namespace

Classes: ParseTreeVisitor

Constant Summary collapse

SimpleSyntax =
/\A#{QuotedFragment}+/o
NamedSyntax =
/\A(#{QuotedFragment})\s*\:\s*(.*)/om

Instance Attribute Summary collapse

Attributes inherited from Tag

#line_number, #nodelist, #parse_context, #tag_name

Instance Method Summary collapse

Methods inherited from Tag

#blank?, disable_tags, #name, parse, #parse, #raw, #render

Methods included from ParserSwitching

#parse_with_selected_parser, #strict_parse_with_error_mode_fallback

Constructor Details

#initialize(tag_name, markup, options) ⇒ Cycle

Returns a new instance of Cycle.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/liquid/tags/cycle.rb', line 23

def initialize(tag_name, markup, options)
  super
  case markup
  when NamedSyntax
    @variables = variables_from_string(Regexp.last_match(2))
    @name      = parse_expression(Regexp.last_match(1))
    @is_named = true
  when SimpleSyntax
    @variables = variables_from_string(markup)
    @name      = @variables.to_s
    @is_named = !@name.match?(/\w+:0x\h{8}/)
  else
    raise SyntaxError, options[:locale].t("errors.syntax.cycle")
  end
end

Instance Attribute Details

#variablesObject (readonly)

Returns the value of attribute variables.



21
22
23
# File 'lib/liquid/tags/cycle.rb', line 21

def variables
  @variables
end

Instance Method Details

#named?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/liquid/tags/cycle.rb', line 39

def named?
  @is_named
end

#render_to_output_buffer(context, output) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/liquid/tags/cycle.rb', line 43

def render_to_output_buffer(context, output)
  context.registers[:cycle] ||= {}

  key       = context.evaluate(@name)
  iteration = context.registers[:cycle][key].to_i

  val = context.evaluate(@variables[iteration])

  if val.is_a?(Array)
    val = val.join
  elsif !val.is_a?(String)
    val = val.to_s
  end

  output << val

  iteration += 1
  iteration = 0 if iteration >= @variables.size

  context.registers[:cycle][key] = iteration
  output
end