Sha256: 3d47a8ac36a33bc63bae2f105aa457cc7a0fccf54351d1feabd2c6cadec48e37

Contents?: true

Size: 1.88 KB

Versions: 12

Compression:

Stored size: 1.88 KB

Contents

module Apotomo
  class JavascriptGenerator
    def initialize(framework)
      raise "No JS framework specified" if framework.blank?
      extend "apotomo/javascript_generator/#{framework}".camelize.constantize
    end
    
    def <<(javascript)
      "#{javascript}"
    end
    
    # Copied from ActionView::Helpers::JavascriptHelper.
    JS_ESCAPE_MAP = {
      '\\'    => '\\\\',
      '</'    => '<\/',
      "\r\n"  => '\n',
      "\n"    => '\n',
      "\r"    => '\n',
      '"'     => '\\"',
      "'"     => "\\'" }

    # Escape carrier returns and single and double quotes for JavaScript segments.
    def self.escape(javascript)
      return javascript.gsub(/(\\|<\/|\r\n|[\n\r"'])/) { JS_ESCAPE_MAP[$1] } if javascript
      
      ''
    end
    
    def escape(javascript)
      self.class.escape(javascript)
    end
    
    module Prototype
      def prototype;            end
      def element(id);          "$(\"#{id}\")"; end
      def xhr(url);             "new Ajax.Request(\"#{url}\")"; end
      def update(id, markup);   element(id) + '.update("'+escape(markup)+'")'; end
      def replace(id, markup);  element(id) + '.replace("'+escape(markup)+'")'; end
    end
    
    module Right
      def right;                end
      def element(id);          "$(\"#{id}\")"; end
      def xhr(url);             "new Xhr(\"#{url}\", {evalScripts:true}).send()"; end
      def update(id, markup);   element(id) + '.update("'+escape(markup)+'")'; end
      def replace(id, markup);  element(id) + '.replace("'+escape(markup)+'")'; end
    end
    
    module Jquery
      def jquery;               end
      def element(id);          "$(\"##{id}\")"; end
      def xhr(url);             "$.ajax({url: \"#{url}\"})"; end
      def update(id, markup);   element(id) + '.html("'+escape(markup)+'")'; end
      def replace(id, markup);  element(id) + '.replaceWith("'+escape(markup)+'")'; end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
apotomo-1.0.5 lib/apotomo/javascript_generator.rb
apotomo-1.0.4 lib/apotomo/javascript_generator.rb
apotomo-1.0.3 lib/apotomo/javascript_generator.rb
apotomo-1.0.2 lib/apotomo/javascript_generator.rb
apotomo-1.0.1 lib/apotomo/javascript_generator.rb
apotomo-1.0.0 lib/apotomo/javascript_generator.rb
apotomo-1.0.0.beta2 lib/apotomo/javascript_generator.rb
apotomo-1.0.0.beta1 lib/apotomo/javascript_generator.rb
apotomo-0.1.4 lib/apotomo/javascript_generator.rb
apotomo-0.1.3 lib/apotomo/javascript_generator.rb
apotomo-0.1.2 lib/apotomo/javascript_generator.rb
apotomo-0.1.1 lib/apotomo/javascript_generator.rb