module UnobtrusiveJavascript PLUGIN_NAME = 'unobtrusive_javascript' PLUGIN_PATH = "#{RAILS_ROOT}/vendor/plugins/#{PLUGIN_NAME}" PLUGIN_ASSET_PATH = "#{PLUGIN_PATH}/assets" PLUGIN_CONTROLLER_PATH = "#{PLUGIN_PATH}/lib/controllers" PLUGIN_VIEW_PATH = "#{PLUGIN_PATH}/lib/views" class Settings cattr_accessor :use_fake_script_links @@use_fake_script_links = false end def self.use_fake_script_links self::Settings.use_fake_script_links = true ActionController::Routing::Routes.add_route "/behaviours/event_selectors.js", :controller => "unobtrusive_javascript", :action => "event_selectors" ActionController::Routing::Routes.add_route "/behaviours/dynamic.js", :controller => "unobtrusive_javascript", :action => "generate" end module ControllerMethods def self.included(base) base.class_eval { before_filter :initialise_js_behaviours } base.class_eval { after_filter :store_js_behaviours } end def register_js_behaviour(selector, behaviour) @js_behaviours = [] if @js_behaviours.nil? @js_behaviours << { :selector => selector, :js_behaviour => behaviour } end def initialise_js_behaviours @js_behaviours = [] end def reset_js_behaviours session[:js_behaviours] = nil end def js_behaviours session[:js_behaviours] end def store_js_behaviours session[:js_behaviours] = @js_behaviours end end module Helpers def unobtrusive_javascript_files unless UnobtrusiveJavascript::Settings.use_fake_script_links output = '' output << '' else output = javascript_include_tag("/behaviours/event_selectors") output << javascript_include_tag("/behaviours/dynamic") end output end def register_js_behaviour(selector, behaviour) @controller.register_js_behaviour(selector, behaviour) end def behaviour_blocks_for(rules) blocks = rules.collect { |rule| "\"#{rule[:selector]}\": function(element, event) {\n #{rule[:js_behaviour]} \n}"} blocks.join(",") end end end