Subscribed unsubscribe Subscribe Subscribe

Kentaro Kuribayashi's blog

Software Engineering, Management, Books, and Daily Journal.

ruby-jquery: jQuery Expression Generator

String-jQuery written by id:motemen intrigued me. I tried to port it to Ruby:

It's almost the same as the original one except one big difference.

require 'jquery'

jQuery()                                       #=> jQuery()
jQuery('a')                                    #=> jQuery("a")
jQuery(:document)                              #=> jQuery(document)
jQuery('a').text()                             #=> jQuery("a").text()
jQuery('a').text('aaa')                        #=> jQuery("a").text("aaa")
jQuery('a').foo(['a', 'b'])                    #=> jQuery("a").foo(["a","b"])
jQuery('a').foo({'a' => 'b'})                  #=> jQuery("a").foo({"a":"b"})
jQuery('a').click(->(f) { f.e 'return true' }) #=> jQuery("a").click(function (e) { return true })

jQuery('#content').show().on('click', 'a', ->(f) { f.e 'return true' })
#=> jQuery("#content").show().on("click","a",function (e) { return true })

The difference is this Ruby porting can't handle JavaScript property access like below:

  • jQuery.ajax(...)
  • jQuery('a').length

However, can I achieve it with Ruby?