Last Updated: March 07, 2016
·
1.999K
· david morrow

Create Dynamic Bookmarklets with Ruby

I recently had the need for a dynamic bookmarklet. I needed the following things..

  • some ruby variables to be cooked into the bookmarklet
  • I didnt want to work with compressed, or minimized code when I wanted to make changes to my javascript
  • the bookmarklet needed to be generated on-demand per user request with the user's api token in the bookmarklet code

My solution was a Ruby helper in my Rails stack to generate the bookmarklet from a Javascript file that had templating keys within.

So say you had a hello.js file like so...

alert("Hello {{user_name}}, It is nice to see you!");

The Ruby Helper to process the Javascript

require 'uri'
module BookmarkletHelper
  def get_bookmarklet(file, hash)
    # read the javascript file
    js = File.open( "#{Rails.root}/app/assets/javascripts/#{file}", 'r' ).read
    # Kill comments.
    js.gsub!( /\/\*.+?\*\/|\/\/.*(?=[\n\r])/, '' )
    # Tabs to spaces
    js.gsub!( /s{\t}{ }gm/, '' )
    # Space runs to one space
    js.gsub!( /s{ +}{ }gm/, '' )         
    # Kill line-leading whitespace
    js.gsub!( /s{^\s+}{}gm/, '' )        
    # Kill line-ending whitespace
    js.gsub!( /s{\s+$}{}gm/, '' )
    # Kill newlines
    js.gsub!( /s{\n}{}gm/, '' )

    hash.each_pair do |k,v|
      js.gsub!( "{{#{k.to_s}}}", v )
    end

    js = URI.escape(js)
    "javascript:(function(){#{js}}());"
  end
end

So Usage would be like this

<% hash = { :user_name => 'David' } %>
<a href="<%= get_bookmarklet('hello.js', hash) %>">Your Bookmarklet</a>

This would create a link to the minimized and formatted for bookmartlet Javascript, with the {{user_name}} replaced with the value from the hash.

1 Response
Add your response

What about putting the JavaScript in a ERB partial? (e.g. http://as-cii.github.io/2014/03/bookmarklet-on-a-href-in-rails.html)

over 1 year ago ·