Module: RubyGaurden::RuntimeEnvironment

Extended by:
ActiveSupport::Concern
Included in:
Bed
Defined in:
lib/ruby_gaurden/runtime_environment.rb

Constant Summary collapse

MAX_CACHE_SIZE =
1000

Instance Method Summary collapse

Instance Method Details

#compile_and_cache(source) ⇒ String

Compiles Ruby source to JavaScript and clears the cache if the limit is reached.

Parameters:

  • source (String)

    Ruby source code.

Returns:

  • (String)

    Compiled JavaScript.



86
87
88
89
90
91
# File 'lib/ruby_gaurden/runtime_environment.rb', line 86

def compile_and_cache(source)
  prune_cache! if self.class.compiled_cache.size >= MAX_CACHE_SIZE
  self.class.compiled_cache[source] = Opal::Compiler.new(source, file: '(execute)', arity_check: true).compile
rescue SyntaxError => e
  raise CompilationError, e.message
end

#execute(source) ⇒ Object

Executes a string of Ruby code within the sandbox instance. Results are cached by the source string to optimize repeated calls.

Parameters:

  • source (String)

    The Ruby code to execute.

Returns:

  • (Object)

    The result of the execution, translated to host Ruby objects.

Raises:



78
79
80
81
# File 'lib/ruby_gaurden/runtime_environment.rb', line 78

def execute(source)
  js = self.class.compiled_cache[source] || compile_and_cache(source)
  eval_compiled_source(js)
end

#prune_cache!Object

Prune the oldest 10% of entries (at least 1) to avoid performance cliffs. Since Ruby Hashes maintain insertion order, this behaves like FIFO.



95
96
97
98
99
100
101
102
# File 'lib/ruby_gaurden/runtime_environment.rb', line 95

def prune_cache!
  self
    .class
    .compiled_cache
    .keys
    .first([1, MAX_CACHE_SIZE / 10].max)
    .each { |k| self.class.compiled_cache.delete(k) }
end