Module: CompEx::Rails::Helpers

Defined in:
lib/compex/rails/helpers.rb

Instance Method Summary collapse

Instance Method Details

#compex_scriptsObject



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/compex/rails/helpers.rb', line 30

def compex_scripts
  buf    = output_buffer
  marker = buf.length

  buf.compex_after_render(marker) do |final_buffer, at|
    scripts = view_flow.get(:compex_scripts)
    next if scripts.blank?
    final_buffer.insert(at, scripts.to_s)
  end

  ActiveSupport::SafeBuffer.new
end

#compex_stylesObject



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/compex/rails/helpers.rb', line 17

def compex_styles
  buf    = output_buffer
  marker = buf.length

  buf.compex_after_render(marker) do |final_buffer, at|
    styles = view_flow.get(:compex_styles)
    next if styles.blank?
    final_buffer.insert(at, styles.to_s)
  end

  ActiveSupport::SafeBuffer.new
end

#component(component_class, **props, &block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/compex/rails/helpers.rb', line 4

def component(component_class, **props, &block)
  slot_html = props.key?(:children) ? props.delete(:children) : nil
  slot_html = capture(&block) if block_given?

  component = component_class.new(**props)
  rendered = slot_html.nil? ? component.render_html : component.render_html(children: slot_html)

  hashes = Array(component.required_hashes).compact
  register_hashes(hashes)

  rendered.respond_to?(:html_safe) ? rendered.html_safe : rendered
end

#register_hashes(hashes) ⇒ Object



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

def register_hashes(hashes)
  state = CompEx::Rails::RequestState
  state.rendered_style_hashes ||= Set.new
  state.rendered_script_hashes ||= Set.new

  hashes.each do |hash|
    source = CompEx::AssetProvider.provide(hash)
    next unless source

    case hash[...2]
    when "j_"
      next unless state.rendered_script_hashes.add?(hash)
      view_flow.append(:compex_scripts,
        (:script, source.html_safe, "type" => "text/javascript", "cx-asset" => hash))
    when "c_"
      next unless state.rendered_style_hashes.add?(hash)
      view_flow.append(:compex_styles,
        (:style, source.html_safe, "cx-asset" => hash))
    end
  end
end