Module: Uprb::RequireReplacer

Defined in:
lib/uprb/require_replacer.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.mappingObject (readonly)

Returns the value of attribute mapping.



10
11
12
# File 'lib/uprb/require_replacer.rb', line 10

def mapping
  @mapping
end

Class Method Details

.pack(source_path, dest_path: nil, requires: [], dynamic: false, script_argv: [], skip_disable_gems: false, skip_ruby_path_replace: false) ⇒ Object



12
13
14
15
16
17
18
19
20
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
# File 'lib/uprb/require_replacer.rb', line 12

def pack(source_path, dest_path: nil, requires: [], dynamic: false, script_argv: [], skip_disable_gems: false, skip_ruby_path_replace: false)
  source = File.read(source_path)
  mapping = build_mapping(source_path, requires, dynamic, script_argv)
  embedded, external = build_payload(mapping)
  ruby_source = source_with_require_hook(source, requires)
  main_iseq = RubyVM::InstructionSequence.compile(ruby_source, source_path, source_path)
  payload = Marshal.dump({
    embedded: embedded,
    external: external,
    main: main_iseq.to_binary
  })

  shebang = resolve_shebang(source, skip_ruby_path_replace: skip_ruby_path_replace, skip_disable_gems: skip_disable_gems)
  body = <<~RUBY
    DATA.binmode
    data = Marshal.load(DATA)

    EMBEDDED_ISEQ = data.fetch(:embedded)
    REQUIRE_MAP = data.fetch(:external)

    iseq = RubyVM::InstructionSequence.load_from_binary(data.fetch(:main))
    iseq.eval
    __END__
  RUBY

  if shebang
    program = "#{shebang}\n#{body}#{payload}"
    return program unless dest_path
    File.write(dest_path, program)
    FileUtils.chmod("+x", dest_path)
  else
    program = body + payload
    return program unless dest_path
    File.write(dest_path, program)
  end
end