DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Alexey has posted 28 posts at DZone. View Full User Profile

Migrating Rails&RJS From Prototype To JQuery

04.15.2011
| 5300 views |
  • submit to reddit
        I was changing prototype to jsquery in my Rails app. To make my AJAX+RJS stuff work I tried jrails gem. For some reason AJAX responses were rendedered to whole page, instead of evaluating the returned JS. So i did the hack. I took this piece of jrails and put it in my /lib folder.

module ActionView
  module Helpers
    module PrototypeHelper
      class JavaScriptGenerator
        module GeneratorMethods
          unless const_defined? :JQUERY_VAR
            JQUERY_VAR = 'jQuery'
          end

          def insert_html(position, id, *options_for_render)
            insertion = position.to_s.downcase
            insertion = 'append' if insertion == 'bottom'
            insertion = 'prepend' if insertion == 'top'
            call "#{JQUERY_VAR}(\"#{jquery_id(id)}\").#{insertion}", render(*options_for_render)
          end

          def replace_html(id, *options_for_render)
            insert_html(:html, id, *options_for_render)
          end

          def replace(id, *options_for_render)
            call "#{JQUERY_VAR}(\"#{jquery_id(id)}\").replaceWith", render(*options_for_render)
          end

          def remove(*ids)
            call "#{JQUERY_VAR}(\"#{jquery_ids(ids)}\").remove"
          end

          def show(*ids)
            call "#{JQUERY_VAR}(\"#{jquery_ids(ids)}\").show"
          end

          def hide(*ids)
            call "#{JQUERY_VAR}(\"#{jquery_ids(ids)}\").hide"
          end

          def toggle(*ids)
            call "#{JQUERY_VAR}(\"#{jquery_ids(ids)}\").toggle"
          end

          def jquery_id(id)
            id.to_s.count('#.*,>+~:[/ ') == 0 ? "##{id}" : id
          end

          def jquery_ids(ids)
            Array(ids).map{|id| jquery_id(id)}.join(',')
          end

        end
      end
    end
  end
end