Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running jQuery in Ruby

I want to run jQuery in a Ruby application and use it to manipulate an HTML string. (Yes, I know there are other Ruby libraries that can handle that task, but I have a good reason for using jQuery in this case.) Is this possible? I know that I can use ExecJS to execute simple JavaScript code in my Ruby application, but jQuery doesn't seem to be working:

irb(main):001:0> require 'execjs'
=> true
irb(main):002:0> require 'open-uri'
=> true
irb(main):003:0> context = ExecJS.compile(open("http://code.jquery.com/jquery-1.9.1.js").read)
=> <Return omitted for brevity>
irb(main):004:0> context.call("$", "<div>Test</div>")
ExecJS::ProgramError: ReferenceError: window is not defined
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-1.4.0/lib/execjs/external_runtime.rb:68:in `extract_result'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-1.4.0/lib/execjs/external_runtime.rb:28:in `block in exec'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-.4.0/lib/execjs/external_runtime.rb:41:in `compile_to_tempfile'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-.4.0/lib/execjs/external_runtime.rb:27:in `exec'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-.4.0/lib/execjs/external_runtime.rb:19:in `eval'
        from c:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/execjs-.4.0/lib/execjs/external_runtime.rb:33:in `call'
        from (irb):4
        from c:/RailsInstaller/Ruby1.9.3/bin/irb:12:in `<main>'

How do I get this to work?

like image 267
Ajedi32 Avatar asked Nov 30 '25 23:11

Ajedi32


1 Answers

The error message tells you what the problem is:

ExecJS::ProgramError: ReferenceError: window is not defined

jQuery is a library for DOM manipulation. It expects to see all of the usual DOM objects and interfaces, including the window object.

The ExecJS library you're using doesn't provide a DOM or a window object. It provides a JavaScript execution context, but not the same one a browser provides.

You may possibly be able to get this working by using another library such as JSDOM to provide a DOM that jQuery can use. Here is a search that may give some tips.

The first link describes a use of JSDOM and jQuery with ExecJS that may be similar to what you want.

That said, why jQuery? There are several good Ruby HTML parsers including Nokogiri. Why not try one of those?

like image 77
Michael Geary Avatar answered Dec 03 '25 15:12

Michael Geary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!