Class: Twig::Extension::Core

Inherits:
Base
  • Object
show all
Extended by:
ActiveSupport::NumberHelper
Defined in:
lib/twig/extension/core.rb

Constant Summary collapse

DEFAULT_TRIM_CHARS =
" \t\n\r\0\x0B"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#globals

Constructor Details

#initializeCore

Returns a new instance of Core.



12
13
14
15
16
17
# File 'lib/twig/extension/core.rb', line 12

def initialize
  super

  @date_format = '%B %-e, %Y %H:%M'
  @number_format = [0, '.', ',']
end

Instance Attribute Details

#date_format=(value) ⇒ Object (writeonly)

Sets the attribute date_format

Parameters:

  • value

    the value to set the attribute date_format to.



19
20
21
# File 'lib/twig/extension/core.rb', line 19

def date_format=(value)
  @date_format = value
end

#number_format(number, decimal: nil, decimal_point: nil, thousands_separator: nil) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/twig/extension/core.rb', line 270

def number_format(number, decimal: nil, decimal_point: nil, thousands_separator: nil)
  number = 0 if number.nil? || number == ''
  decimal ||= @number_format[0]
  decimal_point ||= @number_format[1]
  thousands_separator ||= @number_format[2]

  options = {
    precision: decimal,
    delimiter: thousands_separator,
    separator: decimal_point,
  }.compact

  self.class.number_to_delimited(
    self.class.number_to_rounded(number, options),
    options
  )
end

#timezoneObject



247
248
249
# File 'lib/twig/extension/core.rb', line 247

def timezone
  @timezone ||= Time.zone
end

Class Method Details

.abs(number) ⇒ Object



288
289
290
# File 'lib/twig/extension/core.rb', line 288

def self.abs(number)
  number.abs
end

.array_every?(object, proc) ⇒ Boolean

Returns:

  • (Boolean)


583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/twig/extension/core.rb', line 583

def self.array_every?(object, proc)
  unless object.respond_to?(:all?)
    raise Error::Runtime, "The \"has every\" test expects a sequence or a mapping, got \"#{object.class.name}\"."
  end

  if object.is_a?(Hash)
    object.each do |k, v|
      if proc.arity == 1
        return false unless proc.call(v)
      elsif !proc.call(v, k)
        return false
      end
    end

    true
  else
    object.all?(&proc)
  end
end

.array_some?(object, proc) ⇒ Boolean

Returns:

  • (Boolean)


603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# File 'lib/twig/extension/core.rb', line 603

def self.array_some?(object, proc)
  unless object.respond_to?(:any?)
    raise Error::Runtime, "The \"has some\" test expects a sequence or a mapping, got \"#{object.class.name}\"."
  end

  if object.is_a?(Hash)
    object.each do |k, v|
      if proc.arity == 1
        return true if proc.call(v)
      elsif proc.call(v, k)
        return true
      end
    end

    false
  else
    object.any?(&proc)
  end
end

.batch(object, count, fill: nil, preserve_keys: true) ⇒ Object

Parameters:

  • object (Array, Hash)
  • count (Integer, Float)
  • fill (Object) (defaults to: nil)
  • preserve_keys (Boolean) (defaults to: true)


515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/twig/extension/core.rb', line 515

def self.batch(object, count, fill: nil, preserve_keys: true)
  return if object.nil?

  hash = object.is_a?(Array) ? object.each_with_index.to_h { |k, v| [v, k] } : object
  size = count.ceil
  last_key = 0

  result = hash.each_slice(size).map do |slice|
    unless preserve_keys
      slice = [*0...size].zip(slice.to_h.values)
    end

    sliced_hash = slice.to_h
    last_key = sliced_hash.keys[-1]

    sliced_hash
  end

  if fill.nil? || result.empty?
    return result
  end

  result[-1] = AutoHash.new.merge(result[-1])

  [*0...(size - result[-1].length)].each do
    result[-1].add(fill)
  end

  result
end

.bool(value) ⇒ Object

Zeroes are false in Twig



983
984
985
986
987
988
989
990
991
# File 'lib/twig/extension/core.rb', line 983

def self.bool(value)
  if !value ||
     (value.respond_to?(:zero?) && value.zero?) ||
     value == ''
    false
  else
    true
  end
end

.capitalize(string) ⇒ Object



399
400
401
# File 'lib/twig/extension/core.rb', line 399

def self.capitalize(string)
  string&.capitalize
end

.column(object, column) ⇒ Object



546
547
548
# File 'lib/twig/extension/core.rb', line 546

def self.column(object, column)
  object.map { |o| o[column] }
end

.compare(a, b) ⇒ Object



759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
# File 'lib/twig/extension/core.rb', line 759

def self.compare(a, b)
  trim_var = ->(value) { trim(value, character_mask: " \t\n\r\v\f") }

  if a.is_a?(Integer) && b.is_a?(String)
    b_trim = trim_var.call(b)

    unless numeric?(b_trim)
      return a.to_s <=> b
    end

    if b_trim.to_i.to_s == b_trim
      return a <=> b_trim.to_i
    else
      return a.to_f <=> b_trim.to_f
    end
  end

  if a.is_a?(String) && b.is_a?(Integer)
    a_trim = trim_var.call(a)

    unless numeric?(a_trim)
      return a <=> b.to_s
    end

    if a_trim.to_i.to_s == a_trim
      return a_trim.to_i <=> b
    else
      return a_trim.to_f <=> b.to_f
    end
  end

  if (a.is_a?(Float) || a.is_a?(Complex)) && b.is_a?(String)
    if a.is_a?(Complex)
      return 1
    end

    b_trim = trim_var.call(b)
    unless numeric?(b_trim)
      return a.to_s <=> b
    end

    return a <=> b_trim.to_f
  end

  if a.is_a?(String) && (b.is_a?(Float) || b.is_a?(Complex))
    if b.is_a?(Complex)
      return 1
    end

    a_trim = trim_var.call(a)
    unless numeric?(a_trim)
      return a <=> b.to_s
    end

    return a_trim.to_f <=> b
  end

  if a.is_a?(String) && b.is_a?(Symbol)
    return a <=> b.to_s
  end

  if a.is_a?(Symbol) && b.is_a?(String)
    return a.to_s <=> b
  end

  a <=> b
end

.constant(constant, object = nil, defined_test: false) ⇒ Object

Parameters:

  • constant (String)
  • object (Object, nil) (defaults to: nil)
  • defined_test (Boolean) (defaults to: false)


327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/twig/extension/core.rb', line 327

def self.constant(constant, object = nil, defined_test: false)
  unless object.nil?
    if defined_test
      return object.class.const_defined?(constant)
    end

    return object.class.const_get(constant)
  end

  if constant.include?('::')
    class_name, _, constant = constant.rpartition('::')
  else
    class_name = Kernel.name
  end

  unless Object.const_defined?(class_name)
    return false if defined_test

    raise Error::Runtime, "Class #{class_name} does not exist."
  end

  klass = Object.const_get(class_name)

  unless klass.const_defined?(constant)
    return false if defined_test

    raise Error::Runtime, "Class #{class_name} does not have a constant #{constant}."
  end

  return true if defined_test

  klass.const_get(constant)
end

.convert_encoding(string, to, from) ⇒ Object



391
392
393
# File 'lib/twig/extension/core.rb', line 391

def self.convert_encoding(string, to, from)
  (string || '').to_s.encode(to, from)
end

.cycle(values, position) ⇒ Object



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/twig/extension/core.rb', line 361

def self.cycle(values, position)
  unless values.respond_to?(:[])
    raise Error::Runtime, 'The "cycle" function only works with arrays'
  end

  unless values.respond_to?(:length)
    raise Error::Runtime, 'The "cycle" function expects a countable sequence as first argument.'
  end

  unless values.length.positive?
    raise Error::Runtime, 'The "cycle" function expects a non-empty sequence.'
  end

  values[position % values.length]
end

.default(object, default = nil) ⇒ Object



688
689
690
691
692
# File 'lib/twig/extension/core.rb', line 688

def self.default(object, default = nil)
  present = object.respond_to?(:empty?) ? !object.empty? : !!object

  present ? object : default
end

.deprecation_notice(message, template, line, package: nil, version: nil) ⇒ Object



994
995
996
997
998
999
# File 'lib/twig/extension/core.rb', line 994

def self.deprecation_notice(message, template, line, package: nil, version: nil)
  package = package ? " (Package: #{package})" : ''
  version = version ? " (Version: #{version})" : ''

  puts "Deprecation Notice: #{message} in #{template} on line #{line}#{package}#{version}"
end

.ensure_hash(value) ⇒ Object



749
750
751
752
753
# File 'lib/twig/extension/core.rb', line 749

def self.ensure_hash(value)
  return value.to_h if value.is_a?(Hash)

  AutoHash.new.add(*value)
end

.enumerable_function(object, function, proc) ⇒ Object



1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
# File 'lib/twig/extension/core.rb', line 1106

def self.enumerable_function(object, function, proc)
  enumerable = Runtime::EnumerableHash.from(object)

  case proc.arity
  when 1
    enumerable.public_send(function) do |_, value|
      proc.call(value)
    end
  when 2
    enumerable.public_send(function) do |key, value|
      proc.call(value, key)
    end
  else
    raise Error::Runtime, "The #{function.to_s.capitalize} method takes 1 or 2 arguments, given #{proc.arity}."
  end
end

.filter(object, proc) ⇒ Object



550
551
552
# File 'lib/twig/extension/core.rb', line 550

def self.filter(object, proc)
  enumerable_function(object, :filter, proc)
end

.find(object, proc) ⇒ Object



623
624
625
# File 'lib/twig/extension/core.rb', line 623

def self.find(object, proc)
  enumerable_function(object, :find, proc)&.dig(1)
end

.first(object) ⇒ Object



662
663
664
665
666
667
# File 'lib/twig/extension/core.rb', line 662

def self.first(object)
  return if object.nil?
  return object[0] if object.is_a?(String)

  (object.is_a?(Hash) ? object.values : object).first
end

.get_attribute(environment, source, object, attribute, type, arguments: {}, defined_test: false, ignore_strict_check: false, lineno: -1,) ⇒ Object

Parameters:



864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
# File 'lib/twig/extension/core.rb', line 864

def self.get_attribute(
  environment, source, object, attribute, type, arguments: {}, defined_test: false,
  ignore_strict_check: false, lineno: -1, &
)
  if type == Template::ARRAY_CALL || object.respond_to?(:[])
    if object.respond_to?(:[]) && (
      (object.is_a?(Array) && attribute.is_a?(Integer) && attribute < object.length) ||
      (
        object.respond_to?(:key?) && (
          object.key?(attribute) ||
          (attribute.respond_to?(:to_sym) && object.key?(attribute.to_sym)) ||
            (attribute.respond_to?(:to_s) && object.key?(attribute.to_s))
        )
      )
    )
      return true if defined_test

      return object[attribute] || (attribute.is_a?(String) ? object[attribute.to_sym] : object[attribute.to_s])
    end

    if type == Template::ARRAY_CALL
      if defined_test
        return false
      end

      if ignore_strict_check || !environment.strict_variables?
        return
      end

      raise Error::Runtime, "Can't find key #{attribute} in #{object.inspect}."
    end
  end

  responds_to = begin
    object.respond_to?(attribute)
  rescue StandardError
    false
  end

  if responds_to
    if defined_test
      return true
    end

    positional = []
    arguments.each do |k, v|
      if !v.is_a?(Runtime::Spread) && k.is_a?(Integer)
        positional << v
      elsif v.is_a?(Runtime::Spread) && v.array?
        positional = [*positional, *v.value]
      end
    end

    kwargs = {}
    arguments.each do |k, v|
      if !v.is_a?(Runtime::Spread) && !k.is_a?(Integer)
        kwargs[k] = v
      elsif v.is_a?(Runtime::Spread) && v.hash?
        kwargs = kwargs.merge(v.value)
      end
    end

    kwargs = kwargs.transform_keys(&:to_sym)

    if positional.length.positive? && kwargs.empty?
      object.send(attribute, *positional, &)
    elsif positional.empty? && kwargs.length.positive?
      object.send(attribute, **kwargs, &)
    elsif positional.length.positive? && kwargs.length.positive?
      object.send(attribute, *positional, **kwargs, &)
    else
      case object
      when Hash, Array
        object[attribute]
      else
        object.send(attribute, &)
      end
    end
  # Constant could be nil but we should return if we find it
  elsif (constant = get_constant(object, attribute.to_s)) && constant[0] == :found
    constant[1]
  else
    return if ignore_strict_check || !environment.strict_variables?

    if defined_test
      return false
    end

    message = if object.nil?
                "Impossible to access an attribute (\"#{attribute}\") on a null variable."
              elsif object.respond_to?(:[]) && !object.is_a?(String)
                keys = object.respond_to?(:keys) ? "with keys \"#{object.keys.join(', ')}\"" : ''
                "Key \"#{attribute}\" for sequence/mapping #{keys} does not exist."
              else
                "Impossible to access an attribute (\"#{attribute}\") on a #{object.class} " \
                  "variable (\"#{object}\")."
              end

    raise Error::Runtime.new(
      message,
      lineno,
      source
    )
  end
end

.get_constant(object, attribute) ⇒ Object



970
971
972
973
974
975
976
977
978
979
980
# File 'lib/twig/extension/core.rb', line 970

def self.get_constant(object, attribute)
  object = object.class unless object.respond_to?(:const_defined?)

  if object.const_defined?(attribute)
    [:found, object.const_get(attribute)]
  else
    [:not_found]
  end
rescue NameError
  [:not_found]
end

.in_filter(value, object) ⇒ Object



827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
# File 'lib/twig/extension/core.rb', line 827

def self.in_filter(value, object)
  return false unless object.respond_to?(:include?)

  if object.is_a?(String)
    return object.include?(value.to_s)
  end

  unless object.respond_to?(:any?)
    return false
  end

  object.any? do |k, v|
    (!v.nil? && compare(value, v)&.zero?) ||
      compare(value, k)&.zero?
  end ||
    object.any? { |v| compare(value, v)&.zero? } ||
    (value == false && in_filter(0, object)) ||
    (value == [] && in_filter(false, object)) ||
    (value == true && in_filter(1, object))
end

.include(environment, context, template, variables = {}, with_context: true, ignore_missing: false, sandboxed: false) ⇒ Object

Parameters:



1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
# File 'lib/twig/extension/core.rb', line 1012

def self.include(
  environment, context, template, variables = {}, with_context: true, ignore_missing: false, sandboxed: false
)
  variables = if with_context
                context.merge(variables)
              else
                context.only(variables)
              end

  # @todo: Missing sandbox

  begin
    loaded = environment.resolve_template(template)
  rescue Error::Loader => e
    unless ignore_missing
      raise e
    end

    return ''
  end

  variables.buffer_and_return do
    loaded.render(variables)
  end
end

.invoke(callable) ⇒ Object



694
695
696
# File 'lib/twig/extension/core.rb', line 694

def self.invoke(callable, *, **)
  callable.call(*, **)
end

.join(value, glue: '', and_glue: nil) ⇒ Object



453
454
455
456
457
458
459
460
461
462
463
# File 'lib/twig/extension/core.rb', line 453

def self.join(value, glue: '', and_glue: nil)
  return value unless value.respond_to?(:to_a)

  value = value.values if value.respond_to?(:values)
  value = value.to_a if value.respond_to?(:to_a)

  return value.join(glue) if and_glue.nil? || and_glue == glue
  return value[0] if value.length == 1

  value[..-2].join(glue) + and_glue.to_s + value[-1].to_s
end

.json_encode(object) ⇒ Object



387
388
389
# File 'lib/twig/extension/core.rb', line 387

def self.json_encode(object)
  object.respond_to?(:to_json) ? object.to_json : '{}'
end

.keys(object) ⇒ Object



676
677
678
679
680
# File 'lib/twig/extension/core.rb', line 676

def self.keys(object)
  return object.keys if object.respond_to?(:keys)

  (0...object.length).to_a
end

.last(object) ⇒ Object



669
670
671
672
673
674
# File 'lib/twig/extension/core.rb', line 669

def self.last(object)
  return if object.nil?
  return object[-1] if object.is_a?(String)

  (object.is_a?(Hash) ? object.values : object).last
end

.length(object) ⇒ Object



639
640
641
642
643
644
645
# File 'lib/twig/extension/core.rb', line 639

def self.length(object)
  return object.length if object.respond_to?(:length)
  return object.count if object.respond_to?(:count)
  return object.to_s.length unless object.method(:to_s).owner == Kernel

  1
end

.lower(string) ⇒ Object



407
408
409
# File 'lib/twig/extension/core.rb', line 407

def self.lower(string)
  string&.downcase
end

.map(object, proc) ⇒ Object



554
555
556
557
558
559
560
561
562
# File 'lib/twig/extension/core.rb', line 554

def self.map(object, proc)
  result = enumerable_function(object, :map, proc)

  if object.is_a?(Hash)
    object.keys.zip(result).to_h
  else
    result
  end
end

.matches(regexp, string) ⇒ Object



848
849
850
851
852
853
854
855
856
857
858
859
860
861
# File 'lib/twig/extension/core.rb', line 848

def self.matches(regexp, string)
  return false if string.nil?

  if regexp.respond_to?(:match) && (matches = regexp.match(%r{\A/([^/]*)/(.*)\z}))
    modifiers = matches[2].empty? ? '' : "(?#{matches[2]})"
    regex = /#{modifiers}#{matches[1]}/
  else
    regex = /#{regex}/
  end

  string.to_s.match?(regex)
rescue RegexpError => e
  raise Error::Runtime, "Invalid regular expression passed to matches: #{e.message}"
end

.max(*args) ⇒ Object



308
309
310
311
312
# File 'lib/twig/extension/core.rb', line 308

def self.max(*args)
  args = args[0] if args&.length&.== 1
  args = args.values if args.is_a?(Hash)
  args.max
end

.merge(first, *rest) ⇒ Object



501
502
503
504
505
506
507
508
509
# File 'lib/twig/extension/core.rb', line 501

def self.merge(first, *rest)
  if first.is_a?(Hash)
    [first, *rest].reduce(&:merge)
  else
    [first, *rest].reduce do |array, current|
      array.concat(current.respond_to?(:values) ? current.values : current)
    end
  end
end

.min(*args) ⇒ Object



314
315
316
317
318
# File 'lib/twig/extension/core.rb', line 314

def self.min(*args)
  args = args[0] if args&.length&.== 1
  args = args.values if args.is_a?(Hash)
  args.min
end

.nl2br(string) ⇒ Object



437
438
439
# File 'lib/twig/extension/core.rb', line 437

def self.nl2br(string)
  string.gsub("\n", "<br>\n")
end

.numeric?(value) ⇒ Boolean

Returns:

  • (Boolean)


755
756
757
# File 'lib/twig/extension/core.rb', line 755

def self.numeric?(value)
  Float(value, exception: false)
end

.parse_block_function(parser, fake_node, args, line) ⇒ Object

Parameters:



1071
1072
1073
1074
1075
1076
1077
1078
# File 'lib/twig/extension/core.rb', line 1071

def self.parse_block_function(parser, fake_node, args, line)
  fake_function = TwigFunction.new('block', ->(name, template = nil) {})
  positional, = Util::CallableArgumentsExtractor.
    new(fake_node, fake_function, parser.environment).
    extract_arguments(args)

  Node::Expression::BlockReference.new(positional[0], positional[1], line)
end

.parse_loop_function(parser, fake_node, args, line) ⇒ Object

Parameters:



1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'lib/twig/extension/core.rb', line 1082

def self.parse_loop_function(parser, fake_node, args, line)
  fake_function = TwigFunction.new('loop', ->(iterator) {})
  positional, = Util::CallableArgumentsExtractor.
    new(fake_node, fake_function, parser.environment).
    extract_arguments(args)

  recurse_args = Node::Expression::Hash.new(AutoHash.new.add(
    Node::Expression::Constant.new(0, line),
    positional[0]
  ), line)
  expr = Node::Expression::GetAttribute.new(
    Node::Expression::Variable::Context.new('loop', line),
    Node::Expression::Constant.new('call', line),
    recurse_args,
    Template::METHOD_CALL,
    line
  )
  expr.attributes[:is_generator] = true
  expr = Node::Expression::Filter::Raw.new(expr)
  expr.attributes[:is_generator] = true

  expr
end

.parse_parent_function(parser, fake_node, args, line) ⇒ Object

Parameters:



1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
# File 'lib/twig/extension/core.rb', line 1049

def self.parse_parent_function(parser, fake_node, args, line)
  unless (block_name = parser.peek_block_stack)
    raise Error::Syntax.new(
      'Calling the "parent" function outside of a block is forbidden.',
      line,
      parser.stream.source
    )
  end

  unless parser.inheritance?
    raise Error::Syntax.new(
      'Calling the "parent" function on a template that does not call "extends" or "use" is forbidden.',
      line,
      parser.stream.source
    )
  end

  Node::Expression::Parent.new(block_name, line)
end

.pluralize(string, count = nil) ⇒ Object



445
446
447
# File 'lib/twig/extension/core.rb', line 445

def self.pluralize(string, count = nil)
  string.pluralize(count)
end

.random(charset, values = nil, max = nil) ⇒ Object



698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
# File 'lib/twig/extension/core.rb', line 698

def self.random(charset, values = nil, max = nil)
  if values.nil?
    return max.nil? ? rand : rand(0..max.to_i)
  end

  if values.is_a?(Integer) || values.is_a?(Float)
    if max.nil?
      if values.negative?
        max = 0
        min = values
      else
        max = values
        min = 0
      end
    else
      min = values
    end

    return rand(min.to_i..max.to_i)
  end

  if values.is_a?(String)
    return '' if values.empty?

    if charset != 'UTF-8'
      values = convert_encoding(values, 'UTF-8', charset)
    end

    # Unicode version of string split - split at all positions, but not after start and not before end
    values = values.chars

    if charset != 'UTF-8'
      values = values.map { |value| convert_encoding(value, charset, 'UTF-8') }
    end
  end

  # Check if values is iterable (responds to each and has length/size)
  unless values.respond_to?(:each) && (values.respond_to?(:length) || values.respond_to?(:size))
    return values
  end

  # Convert to array if it's a hash or other enumerable
  values = values.is_a?(Hash) ? values.values : values.to_a

  if values.empty?
    raise Error::Runtime, 'The "random" function cannot pick from an empty sequence or mapping.'
  end

  values.sample
end

.range(low, high, step: 1) ⇒ Object



320
321
322
# File 'lib/twig/extension/core.rb', line 320

def self.range(low, high, step: 1)
  Range.new(low, high).step(step)
end

.reduce(object, proc, initial = nil) ⇒ Object



564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# File 'lib/twig/extension/core.rb', line 564

def self.reduce(object, proc, initial = nil)
  accumulator = initial

  case proc.arity
  when 2
    (object.is_a?(Hash) ? object.values : object).each do |value|
      accumulator = proc.call(accumulator, value)
    end
  when 3
    (object.is_a?(Hash) ? object : object.each_with_index).each do |key, value|
      accumulator = proc.call(accumulator, value, key)
    end
  else
    raise Error::Runtime, "Reduce takes 2 or 3 arguments, given #{proc.arity}."
  end

  accumulator
end

.replace(string, from) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/twig/extension/core.rb', line 255

def self.replace(string, from)
  return if string.nil?

  unless from.is_a?(Hash) || from.is_a?(Array)
    raise Error::Runtime, "The \"replace\" filter expects a sequence or a mapping, got \"#{from.class}\"."
  end

  from = ensure_hash(from)
  regex = Regexp.union(
    *from.keys.map(&:to_s)
  )

  string.gsub(regex, from.transform_keys(&:to_s))
end

.reverse(object, preserve_keys: false) ⇒ Object



627
628
629
630
631
# File 'lib/twig/extension/core.rb', line 627

def self.reverse(object, preserve_keys: false)
  return if object.nil?

  object.is_a?(Hash) ? object.to_a.reverse.to_h : object.reverse
end

.round(value, precision: 0, method: :common) ⇒ Object



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/twig/extension/core.rb', line 292

def self.round(value, precision: 0, method: :common)
  value = value.to_f
  method = method.to_sym

  return value.round(precision) if method == :common

  unless i[ceil floor].include?(method)
    raise Error::Runtime, 'The "round" filter only supports the "common", "ceil", and "floor" methods'
  end

  rounded = (value * (10.0**precision)).public_send(method) / (10.0**precision)
  rounded = rounded.to_i unless precision.positive?

  rounded&.zero? ? 0 : rounded
end

.shuffle(object) ⇒ Object



633
634
635
636
637
# File 'lib/twig/extension/core.rb', line 633

def self.shuffle(object)
  return object.chars.shuffle.join if object.is_a?(String)

  object.is_a?(Hash) ? object.values.shuffle : object.shuffle
end

.singularize(string, count = nil) ⇒ Object



441
442
443
# File 'lib/twig/extension/core.rb', line 441

def self.singularize(string, count = nil)
  string.singularize(count)
end

.slice(object, start, length = nil, preserve_keys: false) ⇒ Object



647
648
649
650
651
652
653
654
655
656
657
658
659
660
# File 'lib/twig/extension/core.rb', line 647

def self.slice(object, start, length = nil, preserve_keys: false)
  if object.is_a?(Hash)
    object, keys = [object.values, object.keys]
    preserve_keys = true
  end

  values = length.nil? ? object[start...] : object[start, length]

  return values unless preserve_keys

  keys ||= [*0...object.length]
  keys = length.nil? ? keys[start...] : keys[start, length]
  keys.zip(values).to_h
end

.slug(string, separator: '-', locale: 'en') ⇒ Object



449
450
451
# File 'lib/twig/extension/core.rb', line 449

def self.slug(string, separator: '-', locale: 'en')
  string.parameterize(separator:, locale:)
end

.sort(object, arrow = nil) ⇒ Object

Parameters:

  • object (Hash, Array, Enumerable)


491
492
493
494
495
496
497
498
499
# File 'lib/twig/extension/core.rb', line 491

def self.sort(object, arrow = nil)
  if arrow.nil?
    object.is_a?(Hash) ? object.sort { |a, b| a[1] <=> b[1] }.to_h : object.sort
  else
    object.sort { |a, b| arrow.call(a, b) }.then do |sorted|
      object.is_a?(Hash) ? sorted.to_h : sorted
    end
  end
end

.source(environment, name, ignore_missing: false) ⇒ Object

Parameters:

  • environment (Environment)
  • name (String)
  • ignore_missing (Boolean) (defaults to: false)


1041
1042
1043
1044
1045
# File 'lib/twig/extension/core.rb', line 1041

def self.source(environment, name, ignore_missing: false)
  environment.loader.get_source_context(name).code
rescue Error::Loader => e
  raise e unless ignore_missing
end

.split(charset, value, delimiter, limit: nil) ⇒ Object



465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# File 'lib/twig/extension/core.rb', line 465

def self.split(charset, value, delimiter, limit: nil)
  value ||= ''

  unless delimiter == ''
    return value.split(delimiter) if limit.nil?
    return value.split(delimiter, limit) if limit >= 0

    return value.split(delimiter)[0...limit]
  end

  if limit.nil? || limit <= 1
    return value.chars
  end

  length = value.length

  if limit.nil? || length < limit
    return [value]
  end

  [*0..(length / limit).ceil].map do |i|
    value[i * limit, limit]
  end
end

.sprintf(string, *values) ⇒ Object



251
252
253
# File 'lib/twig/extension/core.rb', line 251

def self.sprintf(string, *values)
  format(string || '', *values)
end

.strip_tags(string, tags: []) ⇒ Object



411
412
413
# File 'lib/twig/extension/core.rb', line 411

def self.strip_tags(string, tags: [])
  Sanitize.fragment(string || '', elements: tags)
end

.test_empty?(object) ⇒ Boolean

Returns:

  • (Boolean)


1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/twig/extension/core.rb', line 1001

def self.test_empty?(object)
  object.nil? ||
    (object == false) ||
    (object.respond_to?(:empty?) && object.empty?) ||
    (object.respond_to?(:length) && (object.length&.== 0)) || # rubocop:disable Style/ZeroLengthPredicate
    (object.respond_to?(:size) && (object.size&.== 0)) || # rubocop:disable Style/ZeroLengthPredicate
    (object.respond_to?(:to_s) && (object.to_s == ''))
end

.title_case(string) ⇒ Object



395
396
397
# File 'lib/twig/extension/core.rb', line 395

def self.title_case(string)
  string&.titleize
end

.trim(string, character_mask: DEFAULT_TRIM_CHARS, side: :both) ⇒ Object



415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/twig/extension/core.rb', line 415

def self.trim(string, character_mask: DEFAULT_TRIM_CHARS, side: :both)
  return string if character_mask.nil? || character_mask.empty?
  return if string.nil?

  side = side.to_sym
  safe = string.html_safe?

  unless i[left right both].include?(side)
    raise Error::Runtime, 'Trimming side must be "left", "right" or "both".'
  end

  if i[left both].include?(side)
    string = string.gsub(/\A[#{Regexp.escape(character_mask)}]*/, '')
  end

  if i[right both].include?(side)
    string = string.gsub(/[#{Regexp.escape(character_mask)}]*\z/, '')
  end

  safe && character_mask == DEFAULT_TRIM_CHARS ? string.html_safe : string
end

.upper(string) ⇒ Object



403
404
405
# File 'lib/twig/extension/core.rb', line 403

def self.upper(string)
  string&.upcase
end

.url_encode(url) ⇒ Object



377
378
379
380
381
382
383
384
385
# File 'lib/twig/extension/core.rb', line 377

def self.url_encode(url)
  if url.respond_to?(:map)
    require 'uri'
    URI.encode_www_form(url || {}).gsub('+', '%20')
  else
    require 'cgi'
    CGI.escape(url || '').gsub('+', '%20')
  end
end

.values(object) ⇒ Object



682
683
684
685
686
# File 'lib/twig/extension/core.rb', line 682

def self.values(object)
  return object.values if object.respond_to?(:values)

  object.to_a
end

Instance Method Details

#convert_date(date = nil, timezone: self.timezone) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
# File 'lib/twig/extension/core.rb', line 235

def convert_date(date = nil, timezone: self.timezone)
  if date == 'now' || date.nil?
    date = DateTime.now
  elsif date.is_a?(Integer)
    date = Time.then { |t| timezone == false ? t : t.zone }.at(date).to_datetime
  elsif date.is_a?(String)
    date = Time.then { |t| timezone == false ? t : t.zone }.parse(date)
  end

  timezone == false ? date : date.in_time_zone(timezone)
end

#expression_parsersObject



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
56
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/twig/extension/core.rb', line 21

def expression_parsers
  unary = ExpressionParser::Prefix::Unary
  binary = ExpressionParser::Infix::Binary

  [
    # Unary operators
    unary.new(Node::Expression::Unary::Not, 'not', 70),
    unary.new(Node::Expression::Unary::Spread, '...', 512, description: 'Spread Operator'),
    unary.new(Node::Expression::Unary::Neg, '-', 500),
    unary.new(Node::Expression::Unary::Pos, '+', 500),

    # Binary operators
    binary.new(
      Node::Expression::Binary::Elvis, '?:', 5, binary::RIGHT,
      description: 'Elvis operator (a ?: b)', aliases: ['? :']
    ),
    binary.new(
      Node::Expression::Binary::NullCoalesce, '??', 5, binary::RIGHT,
      description: 'Null coalescing operator (a ?? b)'
    ),
    binary.new(Node::Expression::Binary::Or, 'or', 10),
    binary.new(Node::Expression::Binary::Xor, 'xor', 12),
    binary.new(Node::Expression::Binary::And, 'and', 15),
    binary.new(Node::Expression::Binary::BitwiseOr, 'b-or', 16),
    binary.new(Node::Expression::Binary::BitwiseXor, 'b-xor', 17),
    binary.new(Node::Expression::Binary::BitwiseAnd, 'b-and', 16),
    binary.new(Node::Expression::Binary::Equal, '==', 20),
    binary.new(Node::Expression::Binary::NotEqual, '!=', 20),
    binary.new(Node::Expression::Binary::Spaceship, '<=>', 20),
    binary.new(Node::Expression::Binary::Less, '<', 20),
    binary.new(Node::Expression::Binary::Greater, '>', 20),
    binary.new(Node::Expression::Binary::LessEqual, '<=', 20),
    binary.new(Node::Expression::Binary::GreaterEqual, '>=', 20),
    binary.new(Node::Expression::Binary::NotIn, 'not in', 20),
    binary.new(Node::Expression::Binary::In, 'in', 20),
    binary.new(Node::Expression::Binary::Matches, 'matches', 20),
    binary.new(Node::Expression::Binary::StartsWith, 'starts with', 20),
    binary.new(Node::Expression::Binary::EndsWith, 'ends with', 20),
    binary.new(Node::Expression::Binary::HasSome, 'has some', 20),
    binary.new(Node::Expression::Binary::HasEvery, 'has every', 20),
    binary.new(Node::Expression::Binary::Range, '..', 25),
    binary.new(Node::Expression::Binary::Add, '+', 30),
    binary.new(Node::Expression::Binary::Sub, '-', 30),
    binary.new(Node::Expression::Binary::Concat, '~', 27),
    binary.new(Node::Expression::Binary::Mul, '*', 60),
    binary.new(Node::Expression::Binary::Div, '/', 60),
    binary.new(Node::Expression::Binary::FloorDiv, '//', 60, description: 'Floor division'),
    binary.new(Node::Expression::Binary::Mod, '%', 60),
    binary.new(Node::Expression::Binary::Power, '**', 200, binary::RIGHT, description: 'Exponentiation operator'),

    # Ternary operator
    ExpressionParser::Infix::ConditionalTernary.new,

    # Twig callables
    ExpressionParser::Infix::Is.new,
    ExpressionParser::Infix::IsNot.new,
    ExpressionParser::Infix::Filter.new,
    ExpressionParser::Infix::Function.new,

    # Get attribute operators
    ExpressionParser::Infix::Dot.new,
    ExpressionParser::Infix::SquareBracket.new,

    # Group expression
    ExpressionParser::Prefix::Grouping.new,

    # Arrow function
    ExpressionParser::Infix::Arrow.new,

    # All literals
    ExpressionParser::Prefix::Literal.new,
  ]
end

#filtersObject



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/twig/extension/core.rb', line 95

def filters
  [
    # Formatting filters
    TwigFilter.new('date', method(:format_date)),
    TwigFilter.new('format', static(:sprintf)),
    TwigFilter.new('replace', static(:replace)),
    TwigFilter.new('number_format', method(:number_format)),
    TwigFilter.new('abs', static(:abs)),
    TwigFilter.new('round', static(:round)),

    # Encoding
    TwigFilter.new('url_encode', static(:url_encode)),
    TwigFilter.new('json_encode', static(:json_encode)),
    TwigFilter.new('convert_encoding', static(:convert_encoding)),

    # Strings
    TwigFilter.new('title', static(:title_case)),
    TwigFilter.new('capitalize', static(:capitalize)),
    TwigFilter.new('upper', static(:upper)),
    TwigFilter.new('lower', static(:lower)),
    TwigFilter.new('striptags', static(:strip_tags)),
    TwigFilter.new('trim', static(:trim)),
    TwigFilter.new('nl2br', static(:nl2br), { pre_escape: :html, is_safe: [:html] }),
    TwigFilter.new('plural', static(:pluralize)),
    TwigFilter.new('singular', static(:singularize)),
    TwigFilter.new('slug', static(:slug)),

    # array helpers
    TwigFilter.new('join', static(:join)),
    TwigFilter.new('split', static(:split), needs_charset: true),
    TwigFilter.new('sort', static(:sort)),
    TwigFilter.new('merge', static(:merge)),
    TwigFilter.new('batch', static(:batch)),
    TwigFilter.new('column', static(:column)),
    TwigFilter.new('filter', static(:filter)),
    TwigFilter.new('map', static(:map)),
    TwigFilter.new('reduce', static(:reduce)),
    TwigFilter.new('find', static(:find)),

    # Arrays / Hashes filters
    TwigFilter.new('reverse', static(:reverse)),
    TwigFilter.new('shuffle', static(:shuffle)),
    TwigFilter.new('length', static(:length)),
    TwigFilter.new('slice', static(:slice)),
    TwigFilter.new('first', static(:first)),
    TwigFilter.new('last', static(:last)),

    # iteration and runtime
    TwigFilter.new('keys', static(:keys)),
    TwigFilter.new('values', static(:values)),
    TwigFilter.new('default', static(:default), {
      node_class: Node::Expression::Filter::Default,
    }),
    TwigFilter.new('invoke', static(:invoke)),
  ]
end

#format_date(date, format: nil, timezone: self.timezone) ⇒ Object



229
230
231
232
233
# File 'lib/twig/extension/core.rb', line 229

def format_date(date, format: nil, timezone: self.timezone)
  format ||= @date_format

  convert_date(date, timezone:).strftime(format)
end

#functionsObject



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/twig/extension/core.rb', line 152

def functions
  [
    TwigFunction.new('parent', nil, {
      parser_callable: static(:parse_parent_function),
    }),
    TwigFunction.new('block', nil, {
      parser_callable: static(:parse_block_function),
    }),
    TwigFunction.new('loop', nil, {
      parser_callable: static(:parse_loop_function),
    }),
    TwigFunction.new('max', static(:max)),
    TwigFunction.new('min', static(:min)),
    TwigFunction.new('range', static(:range)),
    TwigFunction.new('constant', static(:constant)),
    TwigFunction.new('cycle', static(:cycle)),
    TwigFunction.new('random', static(:random), needs_charset: true),
    TwigFunction.new('date', method(:convert_date)),
    TwigFunction.new('include', static(:include), {
      needs_environment: true, needs_context: true, is_safe: [:all]
    }),
    TwigFunction.new('source', static(:source), {
      needs_environment: true, is_safe: [:all]
    }),
  ]
end

#node_visitorsObject



223
224
225
226
227
# File 'lib/twig/extension/core.rb', line 223

def node_visitors
  [
    NodeVisitor::Spreader.new,
  ]
end

#testsObject



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/twig/extension/core.rb', line 179

def tests
  [
    TwigTest.new('even', nil, { node_class: Node::Expression::Test::Even }),
    TwigTest.new('odd', nil, { node_class: Node::Expression::Test::Odd }),
    TwigTest.new('defined', nil, { node_class: Node::Expression::Test::Defined }),
    TwigTest.new('same as', nil, {
      node_class: Node::Expression::Test::SameAs, one_mandatory_argument: true
    }),
    TwigTest.new('null', nil, { node_class: Node::Expression::Test::Null }),
    TwigTest.new('nil', nil, { node_class: Node::Expression::Test::Null }),
    TwigTest.new('none', nil, { node_class: Node::Expression::Test::Null }),
    TwigTest.new('divisible by', nil, {
      node_class: Node::Expression::Test::DivisibleBy, one_mandatory_argument: true
    }),
    TwigTest.new('constant', nil, { node_class: Node::Expression::Test::Constant }),
    TwigTest.new('empty', static(:test_empty?)),
    TwigTest.new('iterable', nil, { node_class: Node::Expression::Test::Iterable }),
    TwigTest.new('sequence', nil, { node_class: Node::Expression::Test::Sequence }),
    TwigTest.new('mapping', nil, { node_class: Node::Expression::Test::Mapping }),
  ]
end

#token_parsersObject



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/twig/extension/core.rb', line 201

def token_parsers
  [
    TokenParser::Apply.new,
    TokenParser::Block.new,
    TokenParser::Deprecated.new,
    TokenParser::Do.new,
    TokenParser::Embed.new,
    TokenParser::Extends.new,
    TokenParser::For.new,
    TokenParser::From.new,
    TokenParser::Guard.new,
    TokenParser::Macro.new,
    TokenParser::If.new,
    TokenParser::Import.new,
    TokenParser::Include.new,
    TokenParser::Set.new,
    TokenParser::Use.new,
    TokenParser::With.new,
    TokenParser::Yield.new,
  ]
end