best_in_place 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (74) hide show
  1. data/.gitignore +3 -0
  2. data/Gemfile +4 -0
  3. data/README.md +93 -0
  4. data/Rakefile +2 -0
  5. data/best_in_place.gemspec +22 -0
  6. data/lib/best_in_place.rb +33 -0
  7. data/lib/best_in_place/version.rb +3 -0
  8. data/lib/generators/best_in_place/best_in_place_generator.rb +12 -0
  9. data/public/javascripts/best_in_place.js +244 -0
  10. data/public/javascripts/jquery-1.4.2.min.js +154 -0
  11. data/public/javascripts/jquery.purr.js +161 -0
  12. data/test_app/.gitignore +4 -0
  13. data/test_app/Gemfile +31 -0
  14. data/test_app/Gemfile.lock +80 -0
  15. data/test_app/README +256 -0
  16. data/test_app/Rakefile +7 -0
  17. data/test_app/app/controllers/application_controller.rb +3 -0
  18. data/test_app/app/controllers/users_controller.rb +91 -0
  19. data/test_app/app/helpers/application_helper.rb +2 -0
  20. data/test_app/app/helpers/users_helper.rb +2 -0
  21. data/test_app/app/models/user.rb +15 -0
  22. data/test_app/app/views/layouts/application.html.erb +14 -0
  23. data/test_app/app/views/users/_form.html.erb +43 -0
  24. data/test_app/app/views/users/index.html.erb +21 -0
  25. data/test_app/app/views/users/new.html.erb +5 -0
  26. data/test_app/app/views/users/show.html.erb +56 -0
  27. data/test_app/config.ru +4 -0
  28. data/test_app/config/application.rb +42 -0
  29. data/test_app/config/boot.rb +13 -0
  30. data/test_app/config/database.yml +22 -0
  31. data/test_app/config/environment.rb +5 -0
  32. data/test_app/config/environments/development.rb +26 -0
  33. data/test_app/config/environments/production.rb +49 -0
  34. data/test_app/config/environments/test.rb +35 -0
  35. data/test_app/config/initializers/backtrace_silencers.rb +7 -0
  36. data/test_app/config/initializers/countries.rb +1 -0
  37. data/test_app/config/initializers/inflections.rb +10 -0
  38. data/test_app/config/initializers/mime_types.rb +5 -0
  39. data/test_app/config/initializers/secret_token.rb +7 -0
  40. data/test_app/config/initializers/session_store.rb +8 -0
  41. data/test_app/config/locales/en.yml +5 -0
  42. data/test_app/config/routes.rb +64 -0
  43. data/test_app/db/migrate/20101206205922_create_users.rb +18 -0
  44. data/test_app/db/migrate/20101212170114_add_receive_email_to_user.rb +9 -0
  45. data/test_app/db/migrate/20110115204441_add_description_to_user.rb +9 -0
  46. data/test_app/db/schema.rb +28 -0
  47. data/test_app/db/seeds.rb +14 -0
  48. data/test_app/doc/README_FOR_APP +2 -0
  49. data/test_app/lib/tasks/.gitkeep +0 -0
  50. data/test_app/public/404.html +26 -0
  51. data/test_app/public/422.html +26 -0
  52. data/test_app/public/500.html +26 -0
  53. data/test_app/public/favicon.ico +0 -0
  54. data/test_app/public/images/rails.png +0 -0
  55. data/test_app/public/images/red_pen.png +0 -0
  56. data/test_app/public/javascripts/application.js +64 -0
  57. data/test_app/public/javascripts/best_in_place.js +244 -0
  58. data/test_app/public/javascripts/jquery-1.4.2.min.js +154 -0
  59. data/test_app/public/javascripts/jquery.purr.js +161 -0
  60. data/test_app/public/javascripts/jquery.rest_in_place.js +254 -0
  61. data/test_app/public/javascripts/rails.js +133 -0
  62. data/test_app/public/robots.txt +5 -0
  63. data/test_app/public/stylesheets/.gitkeep +0 -0
  64. data/test_app/public/stylesheets/scaffold.css +56 -0
  65. data/test_app/public/stylesheets/style.css +75 -0
  66. data/test_app/script/rails +6 -0
  67. data/test_app/test/fixtures/users.yml +17 -0
  68. data/test_app/test/functional/users_controller_test.rb +49 -0
  69. data/test_app/test/performance/browsing_test.rb +9 -0
  70. data/test_app/test/test_helper.rb +13 -0
  71. data/test_app/test/unit/helpers/users_helper_test.rb +4 -0
  72. data/test_app/test/unit/user_test.rb +8 -0
  73. data/test_app/vendor/plugins/.gitkeep +0 -0
  74. metadata +155 -0
@@ -0,0 +1,35 @@
1
+ BipApp::Application.configure do
2
+ # Settings specified here will take precedence over those in config/environment.rb
3
+
4
+ # The test environment is used exclusively to run your application's
5
+ # test suite. You never need to work with it otherwise. Remember that
6
+ # your test database is "scratch space" for the test suite and is wiped
7
+ # and recreated between test runs. Don't rely on the data there!
8
+ config.cache_classes = true
9
+
10
+ # Log error messages when you accidentally call methods on nil.
11
+ config.whiny_nils = true
12
+
13
+ # Show full error reports and disable caching
14
+ config.consider_all_requests_local = true
15
+ config.action_controller.perform_caching = false
16
+
17
+ # Raise exceptions instead of rendering exception templates
18
+ config.action_dispatch.show_exceptions = false
19
+
20
+ # Disable request forgery protection in test environment
21
+ config.action_controller.allow_forgery_protection = false
22
+
23
+ # Tell Action Mailer not to deliver emails to the real world.
24
+ # The :test delivery method accumulates sent emails in the
25
+ # ActionMailer::Base.deliveries array.
26
+ config.action_mailer.delivery_method = :test
27
+
28
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
29
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
30
+ # like if you have constraints or database-specific column types
31
+ # config.active_record.schema_format = :sql
32
+
33
+ # Print deprecation notices to the stderr
34
+ config.active_support.deprecation = :stderr
35
+ end
@@ -0,0 +1,7 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4
+ # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5
+
6
+ # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7
+ # Rails.backtrace_cleaner.remove_silencers!
@@ -0,0 +1 @@
1
+ COUNTRIES = { 1, "Spain", 2, "Italy", 3, "Germany", 4, "France" }
@@ -0,0 +1,10 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Add new inflection rules using the following format
4
+ # (all these examples are active by default):
5
+ # ActiveSupport::Inflector.inflections do |inflect|
6
+ # inflect.plural /^(ox)$/i, '\1en'
7
+ # inflect.singular /^(ox)en/i, '\1'
8
+ # inflect.irregular 'person', 'people'
9
+ # inflect.uncountable %w( fish sheep )
10
+ # end
@@ -0,0 +1,5 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Add new mime types for use in respond_to blocks:
4
+ # Mime::Type.register "text/richtext", :rtf
5
+ # Mime::Type.register_alias "text/html", :iphone
@@ -0,0 +1,7 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Your secret key for verifying the integrity of signed cookies.
4
+ # If you change this key, all old signed cookies will become invalid!
5
+ # Make sure the secret is at least 30 characters and all random,
6
+ # no regular words or you'll be exposed to dictionary attacks.
7
+ BipApp::Application.config.secret_token = '757d6525986af9c0cb75690db38ba36fd6c1b6f5badb7f586db2da390e87805099de9f365e4e9ebcbba7e2f5cada3f011d620af4a3610b0b96bb01c10175eb33'
@@ -0,0 +1,8 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ BipApp::Application.config.session_store :cookie_store, :key => '_bip_app_session'
4
+
5
+ # Use the database for sessions instead of the cookie-based default,
6
+ # which shouldn't be used to store highly confidential information
7
+ # (create the session table with "rake db:sessions:create")
8
+ # BipApp::Application.config.session_store :active_record_store
@@ -0,0 +1,5 @@
1
+ # Sample localization file for English. Add more files in this directory for other locales.
2
+ # See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
3
+
4
+ en:
5
+ hello: "Hello world"
@@ -0,0 +1,64 @@
1
+ BipApp::Application.routes.draw do
2
+ resources :users do
3
+ collection do
4
+ get :get_countries, :as => "countries"
5
+ end
6
+ end
7
+
8
+ # The priority is based upon order of creation:
9
+ # first created -> highest priority.
10
+
11
+ # Sample of regular route:
12
+ # match 'products/:id' => 'catalog#view'
13
+ # Keep in mind you can assign values other than :controller and :action
14
+
15
+ # Sample of named route:
16
+ # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
17
+ # This route can be invoked with purchase_url(:id => product.id)
18
+
19
+ # Sample resource route (maps HTTP verbs to controller actions automatically):
20
+ # resources :products
21
+
22
+ # Sample resource route with options:
23
+ # resources :products do
24
+ # member do
25
+ # get 'short'
26
+ # post 'toggle'
27
+ # end
28
+ #
29
+ # collection do
30
+ # get 'sold'
31
+ # end
32
+ # end
33
+
34
+ # Sample resource route with sub-resources:
35
+ # resources :products do
36
+ # resources :comments, :sales
37
+ # resource :seller
38
+ # end
39
+
40
+ # Sample resource route with more complex sub-resources
41
+ # resources :products do
42
+ # resources :comments
43
+ # resources :sales do
44
+ # get 'recent', :on => :collection
45
+ # end
46
+ # end
47
+
48
+ # Sample resource route within a namespace:
49
+ # namespace :admin do
50
+ # # Directs /admin/products/* to Admin::ProductsController
51
+ # # (app/controllers/admin/products_controller.rb)
52
+ # resources :products
53
+ # end
54
+
55
+ # You can have the root of your site routed with "root"
56
+ # just remember to delete public/index.html.
57
+ root :to => "users#index"
58
+
59
+ # See how all your routes lay out with "rake routes"
60
+
61
+ # This is a legacy wild controller route that's not recommended for RESTful applications.
62
+ # Note: This route will make all actions in every controller accessible via GET requests.
63
+ # match ':controller(/:action(/:id(.:format)))'
64
+ end
@@ -0,0 +1,18 @@
1
+ class CreateUsers < ActiveRecord::Migration
2
+ def self.up
3
+ create_table :users do |t|
4
+ t.string :name
5
+ t.string :last_name
6
+ t.string :address
7
+ t.string :email, :null => false
8
+ t.string :zip
9
+ t.string :country
10
+
11
+ t.timestamps
12
+ end
13
+ end
14
+
15
+ def self.down
16
+ drop_table :users
17
+ end
18
+ end
@@ -0,0 +1,9 @@
1
+ class AddReceiveEmailToUser < ActiveRecord::Migration
2
+ def self.up
3
+ add_column :users, :receive_email, :boolean
4
+ end
5
+
6
+ def self.down
7
+ remove_column :users, :receive_email
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ class AddDescriptionToUser < ActiveRecord::Migration
2
+ def self.up
3
+ add_column :users, :description, :text
4
+ end
5
+
6
+ def self.down
7
+ remove_column :users, :description
8
+ end
9
+ end
@@ -0,0 +1,28 @@
1
+ # This file is auto-generated from the current state of the database. Instead
2
+ # of editing this file, please use the migrations feature of Active Record to
3
+ # incrementally modify your database, and then regenerate this schema definition.
4
+ #
5
+ # Note that this schema.rb definition is the authoritative source for your
6
+ # database schema. If you need to create the application database on another
7
+ # system, you should be using db:schema:load, not running all the migrations
8
+ # from scratch. The latter is a flawed and unsustainable approach (the more migrations
9
+ # you'll amass, the slower it'll run and the greater likelihood for issues).
10
+ #
11
+ # It's strongly recommended to check this file into your version control system.
12
+
13
+ ActiveRecord::Schema.define(:version => 20110115204441) do
14
+
15
+ create_table "users", :force => true do |t|
16
+ t.string "name"
17
+ t.string "last_name"
18
+ t.string "address"
19
+ t.string "email", :null => false
20
+ t.string "zip"
21
+ t.string "country"
22
+ t.datetime "created_at"
23
+ t.datetime "updated_at"
24
+ t.boolean "receive_email"
25
+ t.text "description"
26
+ end
27
+
28
+ end
@@ -0,0 +1,14 @@
1
+ # This file should contain all the record creation needed to seed the database with its default values.
2
+ # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
3
+ #
4
+ # Examples:
5
+ #
6
+ # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
7
+ # Mayor.create(:name => 'Daley', :city => cities.first)
8
+
9
+ User.delete_all
10
+
11
+ User.create!(:name => "Lucia", :last_name => "Napoli", :email => "lucianapoli@gmail.com", :address => "Via Roma 99", :zip => "25123", :country => "1", :receive_email => false, :description => "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus a lectus et lacus ultrices auctor. Morbi aliquet convallis tincidunt. Praesent enim libero, iaculis at commodo nec, fermentum a dolor. Quisque eget eros id felis lacinia faucibus feugiat et ante. Aenean justo nisi, aliquam vel egestas vel, porta in ligula. Etiam molestie, lacus eget tincidunt accumsan, elit justo rhoncus urna, nec pretium neque mi et lorem. Aliquam posuere, dolor quis pulvinar luctus, felis dolor tincidunt leo, eget pretium orci purus ac nibh. Ut enim sem, suscipit ac elementum vitae, sodales vel sem.")
12
+ User.create!(:name => "Carmen", :last_name => "Luciago", :email => "carmen@luciago.com", :address => "c/Ambrosio 10", :zip => "21333", :country => "2", :receive_email => true, :description => "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus a lectus et lacus ultrices auctor. Morbi aliquet convallis tincidunt. Praesent enim libero, iaculis at commodo nec, fermentum a dolor. Quisque eget eros id felis lacinia faucibus feugiat et ante. Aenean justo nisi, aliquam vel egestas vel, porta in ligula. Etiam molestie, lacus eget tincidunt accumsan, elit justo rhoncus urna, nec pretium neque mi et lorem. Aliquam posuere, dolor quis pulvinar luctus, felis dolor tincidunt leo, eget pretium orci purus ac nibh. Ut enim sem, suscipit ac elementum vitae, sodales vel sem.")
13
+ User.create!(:name => "Angels", :last_name => "Domènech", :email => "angels@gmail.com", :address => "Avinguda Sant Andreu 1", :zip => "08033", :country => "3", :receive_email => false, :description => "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus a lectus et lacus ultrices auctor. Morbi aliquet convallis tincidunt. Praesent enim libero, iaculis at commodo nec, fermentum a dolor. Quisque eget eros id felis lacinia faucibus feugiat et ante. Aenean justo nisi, aliquam vel egestas vel, porta in ligula. Etiam molestie, lacus eget tincidunt accumsan, elit justo rhoncus urna, nec pretium neque mi et lorem. Aliquam posuere, dolor quis pulvinar luctus, felis dolor tincidunt leo, eget pretium orci purus ac nibh. Ut enim sem, suscipit ac elementum vitae, sodales vel sem.")
14
+ User.create!(:name => "Dominic", :last_name => "Lepoin", :email => "dominiclepoin@gmail.com", :address => "Rue Tour Eiffel 4993", :zip => "11192", :country => "4", :receive_email => true, :description => "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus a lectus et lacus ultrices auctor. Morbi aliquet convallis tincidunt. Praesent enim libero, iaculis at commodo nec, fermentum a dolor. Quisque eget eros id felis lacinia faucibus feugiat et ante. Aenean justo nisi, aliquam vel egestas vel, porta in ligula. Etiam molestie, lacus eget tincidunt accumsan, elit justo rhoncus urna, nec pretium neque mi et lorem. Aliquam posuere, dolor quis pulvinar luctus, felis dolor tincidunt leo, eget pretium orci purus ac nibh. Ut enim sem, suscipit ac elementum vitae, sodales vel sem.")
@@ -0,0 +1,2 @@
1
+ Use this README file to introduce your application and point to useful places in the API for learning more.
2
+ Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
File without changes
@@ -0,0 +1,26 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>The page you were looking for doesn't exist (404)</title>
5
+ <style type="text/css">
6
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
7
+ div.dialog {
8
+ width: 25em;
9
+ padding: 0 4em;
10
+ margin: 4em auto 0 auto;
11
+ border: 1px solid #ccc;
12
+ border-right-color: #999;
13
+ border-bottom-color: #999;
14
+ }
15
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
16
+ </style>
17
+ </head>
18
+
19
+ <body>
20
+ <!-- This file lives in public/404.html -->
21
+ <div class="dialog">
22
+ <h1>The page you were looking for doesn't exist.</h1>
23
+ <p>You may have mistyped the address or the page may have moved.</p>
24
+ </div>
25
+ </body>
26
+ </html>
@@ -0,0 +1,26 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>The change you wanted was rejected (422)</title>
5
+ <style type="text/css">
6
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
7
+ div.dialog {
8
+ width: 25em;
9
+ padding: 0 4em;
10
+ margin: 4em auto 0 auto;
11
+ border: 1px solid #ccc;
12
+ border-right-color: #999;
13
+ border-bottom-color: #999;
14
+ }
15
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
16
+ </style>
17
+ </head>
18
+
19
+ <body>
20
+ <!-- This file lives in public/422.html -->
21
+ <div class="dialog">
22
+ <h1>The change you wanted was rejected.</h1>
23
+ <p>Maybe you tried to change something you didn't have access to.</p>
24
+ </div>
25
+ </body>
26
+ </html>
@@ -0,0 +1,26 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>We're sorry, but something went wrong (500)</title>
5
+ <style type="text/css">
6
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
7
+ div.dialog {
8
+ width: 25em;
9
+ padding: 0 4em;
10
+ margin: 4em auto 0 auto;
11
+ border: 1px solid #ccc;
12
+ border-right-color: #999;
13
+ border-bottom-color: #999;
14
+ }
15
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
16
+ </style>
17
+ </head>
18
+
19
+ <body>
20
+ <!-- This file lives in public/500.html -->
21
+ <div class="dialog">
22
+ <h1>We're sorry, but something went wrong.</h1>
23
+ <p>We've been notified about this issue and we'll take a look at it shortly.</p>
24
+ </div>
25
+ </body>
26
+ </html>
File without changes
Binary file
Binary file
@@ -0,0 +1,64 @@
1
+ // Place your application-specific JavaScript functions and classes here
2
+ // This file is automatically included by javascript_include_tag :defaults
3
+
4
+ $(document).ready(function() {
5
+ /* Activating Best In Place */
6
+ jQuery(".best_in_place").best_in_place()
7
+ });
8
+
9
+ function inspect(obj, maxLevels, level)
10
+ {
11
+ var str = '', type, msg;
12
+
13
+ // Start Input Validations
14
+ // Don't touch, we start iterating at level zero
15
+ if(level == null) level = 0;
16
+
17
+ // At least you want to show the first level
18
+ if(maxLevels == null) maxLevels = 1;
19
+ if(maxLevels < 1)
20
+ return '<font color="red">Error: Levels number must be > 0</font>';
21
+
22
+ // We start with a non null object
23
+ if(obj == null)
24
+ return '<font color="red">Error: Object <b>NULL</b></font>';
25
+ // End Input Validations
26
+
27
+ // Each Iteration must be indented
28
+ str += '<ul>';
29
+
30
+ // Start iterations for all objects in obj
31
+ for(property in obj)
32
+ {
33
+ try
34
+ {
35
+ // Show "property" and "type property"
36
+ type = typeof(obj[property]);
37
+ str += '<li>(' + type + ') ' + property +
38
+ ( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>';
39
+
40
+ // We keep iterating if this property is an Object, non null
41
+ // and we are inside the required number of levels
42
+ if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
43
+ str += inspect(obj[property], maxLevels, level+1);
44
+ }
45
+ catch(err)
46
+ {
47
+ // Is there some properties in obj we can't access? Print it red.
48
+ if(typeof(err) == 'string') msg = err;
49
+ else if(err.message) msg = err.message;
50
+ else if(err.description) msg = err.description;
51
+ else msg = 'Unknown';
52
+
53
+ str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
54
+ }
55
+ }
56
+
57
+ // Close indent
58
+ str += '</ul>';
59
+
60
+ var container = $("<span class='flash-notice' style='top:1em'></span>").html(str);
61
+ container.purr({isSticky:true});
62
+
63
+ return str;
64
+ }
@@ -0,0 +1,244 @@
1
+ /*
2
+ BestInPlace (for jQuery)
3
+ version: 0.1.0 (01/01/2011)
4
+ @requires jQuery >= v1.4
5
+ @requires jQuery.purr to display pop-up windows
6
+
7
+ By Bernat Farrero based on the work of Jan Varwig.
8
+ Examples at http://bernatfarrero.com
9
+
10
+ Licensed under the MIT:
11
+ http://www.opensource.org/licenses/mit-license.php
12
+
13
+ Usage:
14
+
15
+ Attention. Format of JSON given to select inputs is the following way.
16
+ [["name1", "value1"],["name2", "value2"]]
17
+ */
18
+
19
+ function BestInPlaceEditor(e) {
20
+ this.element = jQuery(e)
21
+ this.initOptions()
22
+ this.bindForm()
23
+ this.activator.bind('click', {editor: this}, this.clickHandler)
24
+ }
25
+
26
+ BestInPlaceEditor.prototype = {
27
+ // Public Interface Functions //////////////////////////////////////////////
28
+
29
+ activate : function() {
30
+ var elem = this.element.html()
31
+ this.oldValue = elem
32
+ this.activator.unbind("click", this.clickHandler)
33
+ this.activateForm()
34
+ },
35
+
36
+ abort : function() {
37
+ this.element.html(this.oldValue).bind('click', {editor: this}, this.clickHandler)
38
+ },
39
+
40
+ update : function() {
41
+ var editor = this
42
+ editor.ajax({
43
+ "type" : "post",
44
+ "dataType" : "text",
45
+ "data" : editor.requestData(),
46
+ "success" : function(data){ editor.loadSuccessCallback(data) },
47
+ "error" : function(request, error){ editor.loadErrorCallback(request, error) }
48
+ })
49
+ if (this.formType == "select") {
50
+ editor.element.html(this.values[this.getValue()][1])
51
+ } else if (this.formType == "checkbox") {
52
+ editor.element.html(this.getValue() ? this.values[1] : this.values[0])
53
+ } else editor.element.html(this.getValue())
54
+ },
55
+
56
+ activateForm : function() {
57
+ alert("The form was not properly initialized. activateForm is unbound")
58
+ },
59
+
60
+ // Helper Functions ////////////////////////////////////////////////////////
61
+
62
+ initOptions : function() {
63
+ // Try parent supplied info
64
+ var self = this
65
+ self.element.parents().each(function(){
66
+ self.url = self.url || jQuery(this).attr("data-url")
67
+ self.selectValues = self.selectValues || jQuery(this).attr("data-selectValues")
68
+ self.formType = self.formType || jQuery(this).attr("data-formType")
69
+ self.objectName = self.objectName || jQuery(this).attr("data-object")
70
+ self.attributeName = self.attributeName || jQuery(this).attr("data-attribute")
71
+ })
72
+ // Try Rails-id based if parents did not explicitly supply something
73
+ self.element.parents().each(function(){
74
+ var res
75
+ if (res = this.id.match(/^(\w+)_(\d+)$/i)) {
76
+ self.objectName = self.objectName || res[1]
77
+ }
78
+ })
79
+
80
+ // Load own attributes (overrides all others)
81
+ self.url = self.element.attr("data-url") || self.url || document.location.pathname
82
+ self.selectValues = self.element.attr("data-selectValues") || self.selectValues
83
+ self.formType = self.element.attr("data-formType") || self.formtype || "input"
84
+ self.objectName = self.element.attr("data-object") || self.objectName
85
+ self.attributeName = self.element.attr("data-attribute") || self.attributeName
86
+ self.activator = self.element.attr("data-activator") || self.element
87
+
88
+ if ((self.formType == "select" || self.formType == "checkbox") && self.selectValues != null)
89
+ {
90
+ self.values = jQuery.parseJSON(self.selectValues)
91
+ }
92
+ },
93
+
94
+ bindForm : function() {
95
+ this.activateForm = BestInPlaceEditor.forms[this.formType].activateForm
96
+ this.getValue = BestInPlaceEditor.forms[this.formType].getValue
97
+ },
98
+
99
+ getValue : function() {
100
+ alert("The form was not properly initialized. getValue is unbound")
101
+ },
102
+
103
+ // Trim and Strips HTML from text
104
+ sanitize : function(s) {
105
+ var tmp = document.createElement("DIV")
106
+ tmp.innerHTML = s
107
+ return jQuery.trim(tmp.textContent||tmp.innerText)
108
+ },
109
+
110
+ /* Generate the data sent in the POST request */
111
+ requestData : function() {
112
+ //jq14: data as JS object, not string.
113
+ var data = "_method=put"
114
+ data += "&"+this.objectName+'['+this.attributeName+']='+encodeURIComponent(this.getValue())
115
+ if (window.rails_authenticity_token) {
116
+ data += "&authenticity_token="+encodeURIComponent(window.rails_authenticity_token)
117
+ }
118
+ return data
119
+ },
120
+
121
+ ajax : function(options) {
122
+ options.url = this.url
123
+ options.beforeSend = function(xhr){ xhr.setRequestHeader("Accept", "application/json") }
124
+ try { var ajaxRequest = jQuery.ajax(options) }
125
+ catch(e) { alert("error") }
126
+ return ajaxRequest
127
+ },
128
+
129
+ // Handlers ////////////////////////////////////////////////////////////////
130
+
131
+ loadSuccessCallback : function(data) {
132
+ //jq14: data as JS object, not string.
133
+ if (jQuery.fn.jquery < "1.4") data = eval('(' + data + ')' )
134
+ this.element.html(data[this.objectName])
135
+
136
+ // Binding back after being clicked
137
+ this.element.bind('click', {editor: this}, this.clickHandler)
138
+ },
139
+
140
+ loadErrorCallback : function(request, error) {
141
+ this.element.html(this.oldValue)
142
+
143
+ // Display all error messages from server side validation
144
+ $.each(jQuery.parseJSON(request.responseText), function(index, value) {
145
+ var container = $("<span class='flash-error'></span>").html(index + ': ' + value)
146
+ container.purr()
147
+ })
148
+
149
+ // Binding back after being clicked
150
+ this.element.bind('click', {editor: this}, this.clickHandler)
151
+ },
152
+
153
+ clickHandler : function(event) {
154
+ event.data.editor.activate()
155
+ }
156
+ }
157
+
158
+
159
+ BestInPlaceEditor.forms = {
160
+ "input" : {
161
+ activateForm : function() {
162
+ var form = '<form class="form_in_place" action="javascript:void(0)" style="display:inline;"><input type="text" value="' + this.sanitize(this.oldValue) + '"></form>'
163
+ this.element.html(form)
164
+ this.element.find('input')[0].select()
165
+ this.element.find("form")
166
+ .bind('submit', {editor: this}, BestInPlaceEditor.forms.input.submitHandler)
167
+ this.element.find("input")
168
+ .bind('blur', {editor: this}, BestInPlaceEditor.forms.input.inputBlurHandler)
169
+ },
170
+
171
+ getValue : function() {
172
+ return this.sanitize(this.element.find("input").val())
173
+ },
174
+
175
+ inputBlurHandler : function(event) {
176
+ event.data.editor.abort()
177
+ },
178
+
179
+ submitHandler : function(event) {
180
+ event.data.editor.update()
181
+ return false
182
+ }
183
+ },
184
+
185
+ "select" : {
186
+ activateForm : function() {
187
+ var output = "<form action='javascript:void(0)' style='display:inline;'><select>"
188
+ var selected = ""
189
+ var oldValue = this.oldValue
190
+ $.each(this.values, function(index, value) {
191
+ selected = (value[1] == oldValue ? "selected='selected'" : "")
192
+ output += "<option value='" + index + "' " + selected + ">" + value[1] + "</option>"
193
+ })
194
+ output += "</select></form>"
195
+ this.element.html(output)
196
+ this.element.find("select").bind('change', {editor: this}, BestInPlaceEditor.forms.select.blurHandler)
197
+ },
198
+
199
+ getValue : function() {
200
+ return this.sanitize(this.element.find("select").val())
201
+ },
202
+
203
+ blurHandler : function(event) {
204
+ event.data.editor.update()
205
+ }
206
+ },
207
+
208
+ "checkbox" : {
209
+ activateForm : function() {
210
+ var newValue = Boolean(this.oldValue != this.values[1])
211
+ var output = newValue ? this.values[1] : this.values[0]
212
+ this.element.html(output)
213
+ this.update()
214
+ },
215
+
216
+ getValue : function() {
217
+ return Boolean(this.element.html() == this.values[1])
218
+ }
219
+ },
220
+
221
+ "textarea" : {
222
+ activateForm : function() {
223
+ this.element.html('<form action="javascript:void(0)" style="display:inline;"><textarea>' + this.sanitize(this.oldValue) + '</textarea></form>')
224
+ this.element.find('textarea')[0].select()
225
+ this.element.find("textarea").bind('blur', {editor: this}, BestInPlaceEditor.forms.textarea.blurHandler)
226
+ },
227
+
228
+ getValue : function() {
229
+ return this.sanitize(this.element.find("textarea").val())
230
+ },
231
+
232
+ blurHandler : function(event) {
233
+ event.data.editor.update()
234
+ }
235
+
236
+ }
237
+ }
238
+
239
+ jQuery.fn.best_in_place = function() {
240
+ this.each(function(){
241
+ jQuery(this).data('bestInPlaceEditor', new BestInPlaceEditor(this))
242
+ })
243
+ return this
244
+ }