Module: Futurism::Helpers

Defined in:
lib/futurism/helpers.rb

Defined Under Namespace

Classes: WrappingFuturismElement

Instance Method Summary collapse

Instance Method Details

#futurize(records_or_string = nil, extends:, **options, &block) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/futurism/helpers.rb', line 3

def futurize(records_or_string = nil, extends:, **options, &block)
  if Rails.env.test? && Futurism.skip_in_test
    if records_or_string.nil?
      return render(**options)
    else
      return render(records_or_string, **options)
    end
  end

  options[:eager] = true unless block_given?

  if records_or_string.is_a?(ActiveRecord::Base) || records_or_string.is_a?(ActiveRecord::Relation)
    futurize_active_record(records_or_string, extends: extends, **options, &block)
  elsif records_or_string.is_a?(String)
    html_options = options.delete(:html_options)
    futurize_with_options(extends: extends, partial: records_or_string, locals: options, html_options: html_options, &block)
  else
    futurize_with_options(extends: extends, **options, &block)
  end
end

#futurize_active_record(records, extends:, **options, &block) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/futurism/helpers.rb', line 46

def futurize_active_record(records, extends:, **options, &block)
  Array(records).map.with_index { |record, index|
    placeholder = capture(record, index, &block) if block_given?

    WrappingFuturismElement.new(extends: extends, options: options.merge(model: record), placeholder: placeholder).render
  }.join.html_safe
end

#futurize_with_options(extends:, **options, &block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/futurism/helpers.rb', line 24

def futurize_with_options(extends:, **options, &block)
  collection = options.delete(:collection)
  if collection.nil?
    placeholder = capture(&block) if block_given?

    WrappingFuturismElement.new(extends: extends, placeholder: placeholder, options: options).render
  else
    collection_class_name = collection.try(:klass).try(:name) || collection.first.class.to_s
    as = options.delete(:as) || collection_class_name.underscore
    broadcast_each = options.delete(:broadcast_each) || false

    collection.each_with_index.map { |record, index|
      placeholder = capture(record, index, &block) if block_given?

      WrappingFuturismElement.new(extends: extends, placeholder: placeholder, options: options.deep_merge(
        broadcast_each: broadcast_each,
        locals: {as.to_sym => record, "#{as}_counter".to_sym => index}
      )).render
    }.join.html_safe
  end
end