diff --git a/lib/execjs/external_runtime.rb b/lib/execjs/external_runtime.rb index ec06d3f..5ed9272 100644 --- a/lib/execjs/external_runtime.rb +++ b/lib/execjs/external_runtime.rb @@ -6,14 +6,14 @@ module ExecJS class ExternalRuntime class Context def initialize(runtime, source = "") - source = source.encode('UTF-8') if source.respond_to?(:encode) + source = ExecJS::encode(source) if source.respond_to?(:encode) @runtime = runtime @source = source end def eval(source, options = {}) - source = source.encode('UTF-8') if source.respond_to?(:encode) + source = ExecJS::encode(source) if source.respond_to?(:encode) if /\S/ =~ source exec("return eval(#{json_encode("(#{source})")})") @@ -21,7 +21,7 @@ module ExecJS end def exec(source, options = {}) - source = source.encode('UTF-8') if source.respond_to?(:encode) + source = ExecJS::encode(source) if source.respond_to?(:encode) source = "#{@source}\n#{source}" if @source compile_to_tempfile(source) do |file| diff --git a/lib/execjs/ruby_rhino_runtime.rb b/lib/execjs/ruby_rhino_runtime.rb index df55395..2113941 100644 --- a/lib/execjs/ruby_rhino_runtime.rb +++ b/lib/execjs/ruby_rhino_runtime.rb @@ -2,7 +2,7 @@ module ExecJS class RubyRhinoRuntime class Context def initialize(source = "") - source = source.encode('UTF-8') if source.respond_to?(:encode) + source = ExecJS::encode(source) if source.respond_to?(:encode) @rhino_context = ::Rhino::Context.new fix_memory_limit! @rhino_context @@ -10,7 +10,7 @@ module ExecJS end def exec(source, options = {}) - source = source.encode('UTF-8') if source.respond_to?(:encode) + source = ExecJS::encode(source) if source.respond_to?(:encode) if /\S/ =~ source eval "(function(){#{source}})()", options @@ -18,7 +18,7 @@ module ExecJS end def eval(source, options = {}) - source = source.encode('UTF-8') if source.respond_to?(:encode) + source = ExecJS::encode(source) if source.respond_to?(:encode) if /\S/ =~ source unbox @rhino_context.eval("(#{source})") diff --git a/lib/execjs/runtimes.rb b/lib/execjs/runtimes.rb index cb4d837..52fd81c 100644 --- a/lib/execjs/runtimes.rb +++ b/lib/execjs/runtimes.rb @@ -90,4 +90,28 @@ module ExecJS def self.runtimes Runtimes.runtimes end + + if defined? Encoding + if (!defined?(RUBY_ENGINE) || RUBY_ENGINE != "jruby") + def self.encode(string) + string.encode('UTF-8') + end + else + # workaround for jruby bug http://jira.codehaus.org/browse/JRUBY-6588 + def self.encode(string) + if string.encoding.name == 'ASCII-8BIT' + data = string.dup + data.force_encoding('utf-8') + + unless data.valid_encoding? + raise Encoding::UndefinedConversionError, "Could not encode ASCII-8BIT data #{string.dump} as UTF-8" + end + else + data = string.encode('utf-8') + end + data + end + end + end + end