Module: Snabberb

Defined in:
lib/snabberb.rb,
lib/snabberb/version.rb

Constant Summary collapse

VERSION =
'1.5.1'

Class Method Summary collapse

Class Method Details

.html_script(file, **needs) ⇒ Object

takes in a file and needs calls html on the CamelCased version of the file with the needs



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/snabberb.rb', line 43

def self.html_script(file, **needs)
  klass = file.split('/').last
              .split('.').first
              .split('_').map(&:capitalize).join

  script = <<~RUBY
    #{File.read(file)}
    #{klass}.html(`#{wrap(needs)}`)
  RUBY

  Opal.compile(script).strip.chomp(';')
end

.prerender_script(layout, application, application_id, javascript_include_tags: '', **needs) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/snabberb.rb', line 56

def self.prerender_script(layout, application, application_id, javascript_include_tags: '', **needs)
  needs = wrap(needs)
  attach_func = wrap_s("Opal.#{application}.$attach(\"#{application_id}\", #{needs})")

  <<~JS
    Opal.#{layout}.$html(Opal.hash({
      application: Opal.#{application}.$new(null, #{needs}).$render(),
      javascript_include_tags: '#{javascript_include_tags.gsub("\n", '')}',
      attach_func: #{attach_func}
    }))
  JS
end

.wrap(obj) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/snabberb.rb', line 10

def self.wrap(obj)
  case obj
  when Hash
    wrap_h(obj)
  when Array
    wrap_a(obj)
  when Numeric, TrueClass, FalseClass
    obj
  when nil
    'Opal.nil'
  else
    wrap_s(obj.to_s)
  end
end

.wrap_a(array) ⇒ Object



29
30
31
# File 'lib/snabberb.rb', line 29

def self.wrap_a(array)
  "[#{array.map { |v| wrap(v) }.join(',')}]"
end

.wrap_h(hash) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/snabberb.rb', line 33

def self.wrap_h(hash)
  args = hash.flat_map do |k, v|
    [wrap_s(k), wrap(v)]
  end.join(',')

  "Opal.hash(#{args})"
end

.wrap_s(str) ⇒ Object



25
26
27
# File 'lib/snabberb.rb', line 25

def self.wrap_s(str)
  JSON.generate(str)
end