best_in_place_rails_4 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 34cbc1ecf47517e55aa0e4072157b54613b7d120
4
+ data.tar.gz: f14b06b42decfe3203ef66479cdfb99f7ae72045
5
+ SHA512:
6
+ metadata.gz: 2df8e6d45614f3a55eadc8fdd2ff5a88bcca17a0c261a584f54312a81579f36b8fe34ab796f5daa4f34420c7c795a859684070c22e7a393a88af1aecf69ec735
7
+ data.tar.gz: 87dbf11cd8a896172ceb219c97ac2f27a806ffa3e6c148fa5f5bf3d651d6e01e03bf34052d650022b3a0e8a9758807e92d69372669381468ba0d59f2822270bd
@@ -0,0 +1,22 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ *.bundle
19
+ *.so
20
+ *.o
21
+ *.a
22
+ mkmf.log
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in best_in_place_rails_4.gemspec
4
+ gemspec
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2014 Eric Berry
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,439 @@
1
+ # Best In Place
2
+ **The Unobtrusive in Place editing solution**
3
+
4
+ This is a fork of https://github.com/bernat/best_in_place and is meant to be
5
+ compatible with Rails 4 and Heroku.
6
+
7
+ ##Description
8
+
9
+ **Best in Place** is a jQuery based AJAX Inplace-Editor that takes profit of RESTful server-side controllers to allow users to edit stuff with
10
+ no need of forms. If the server have standard defined REST methods, particularly those to UPDATE your objects (HTTP PUT), then by adding the
11
+ Javascript file to the application it is making all the fields with the proper defined classes to become user in-place editable.
12
+
13
+ The editor works by PUTting the updated value to the server and GETting the updated record afterwards to display the updated value.
14
+
15
+ [**SEE DEMO**](http://bipapp.heroku.com/)
16
+
17
+ ---
18
+
19
+ ##Features
20
+
21
+ - Compatible with text **inputs**
22
+ - Compatible with **textarea**
23
+ - Compatible with **select** dropdown with custom collections
24
+ - Compatible with custom boolean values (same usage of **checkboxes**)
25
+ - Compatible with **jQuery UI Datepickers**
26
+ - Sanitize HTML and trim spaces of user's input on user's choice
27
+ - Displays server-side **validation** errors
28
+ - Allows external activator
29
+ - Allows optional, configurable OK and Cancel buttons for inputs and textareas
30
+ - ESC key destroys changes (requires user confirmation)
31
+ - Autogrowing textarea
32
+ - Helper for generating the best_in_place field only if a condition is satisfied
33
+ - Provided test helpers to be used in your integration specs
34
+ - Custom display methods using a method from your model or an existing rails
35
+ view helper
36
+
37
+ ##Usage of Rails 3 Gem
38
+
39
+ ###best_in_place
40
+ **best_in_place object, field, OPTIONS**
41
+
42
+ Params:
43
+
44
+ - **object** (Mandatory): The Object parameter represents the object itself you are about to modify
45
+ - **field** (Mandatory): The field (passed as symbol) is the attribute of the Object you are going to display/edit.
46
+
47
+ Options:
48
+
49
+ - **:type** It can be only [:input, :textarea, :select, :checkbox, :date (>= 1.0.4)] or if undefined it defaults to :input.
50
+ - **:collection**: In case you are using the :select type then you must specify the collection of values it takes. In case you are
51
+ using the :checkbox type you can specify the two values it can take, or otherwise they will default to Yes and No.
52
+ - **:path**: URL to which the updating action will be sent. If not defined it defaults to the :object path.
53
+ - **:nil**: The nil param defines the content displayed in case no value is defined for that field. It can be something like "click me to edit".
54
+ If not defined it will show *"-"*.
55
+ - **:activator**: Is the DOM object that can activate the field. If not defined the user will making editable by clicking on it.
56
+ - **:ok_button**: (Inputs and textareas only) If set to a string, then an OK button will be shown with the string as its label, replacing save on blur.
57
+ - **:cancel_button**: (Inputs and textareas only) If set to a string, then a Cancel button will be shown with the string as its label.
58
+ - **:sanitize**: True by default. If set to false the input/textarea will accept html tags.
59
+ - **:html_attrs**: Hash of html arguments, such as maxlength, default-value etc.
60
+ - **:inner_class**: Class that is set to the rendered form.
61
+ - **:display_as**: A model method which will be called in order to display
62
+ this field.
63
+ - **:object_name**: Used for overriding the default params key used for the object (the data-object attribute). Useful for e.g. STI scenarios where best_in_place should post to a common controller for different models.
64
+ - **:data**: Hash of custom data attributes to be added to span. Can be used to provide data to the ajax:success callback.
65
+ - **:classes**: Additional classes to apply to the best_in_place span. Accepts either a string or Array of strings
66
+
67
+ ###best_in_place_if
68
+ **best_in_place_if condition, object, field, OPTIONS**
69
+
70
+ It allows us to use best_in_place only if the first new parameter, a
71
+ condition, is satisfied. Specifically:
72
+
73
+ * Will show a normal best_in_place if the condition is satisfied
74
+ * Will only show the attribute from the instance if the condition is not satisfied
75
+
76
+ Say we have something like
77
+
78
+ <%= best_in_place_if condition, @user, :name, :type => :input %>
79
+
80
+ In case *condition* is satisfied, the outcome will be just the same as:
81
+
82
+ <%= best_in_place @user, :name, :type => :input %>
83
+
84
+ Otherwise, we will have the same outcome as:
85
+
86
+ <%= @user.name %>
87
+
88
+ It is a very useful feature to use with, for example, [Ryan Bates](https://github.com/ryanb)' [CanCan](https://github.com/ryanb/cancan), so we only allow BIP edition if the current user has permission to do it.
89
+
90
+ ---
91
+
92
+ ##TestApp and examples
93
+ A [test_app](https://github.com/bernat/best_in_place/tree/master/test_app) was created, and can be seen in action in a [running demo on heroku](http://bipapp.heroku.com).
94
+
95
+ Examples (code in the views):
96
+
97
+ ### Input
98
+
99
+ <%= best_in_place @user, :name, :type => :input %>
100
+
101
+ <%= best_in_place @user, :name, :type => :input, :nil => "Click me to add content!" %>
102
+
103
+ ### Textarea
104
+
105
+ <%= best_in_place @user, :description, :type => :textarea %>
106
+
107
+ <%= best_in_place @user, :favorite_books, :type => :textarea, :ok_button => 'Save', :cancel_button => 'Cancel' %>
108
+
109
+ ### Select
110
+
111
+ <%= best_in_place @user, :country, :type => :select, :collection => [[1, "Spain"], [2, "Italy"], [3, "Germany"], [4, "France"]] %>
112
+
113
+ Of course it can take an instance or global variable for the collection, just remember the structure `[[key, value], [key, value],...]`.
114
+ The key can be a string or an integer.
115
+
116
+ ### Checkbox
117
+
118
+ <%= best_in_place @user, :receive_emails, :type => :checkbox, :collection => ["No, thanks", "Yes, of course!"] %>
119
+
120
+ The first value is always the negative boolean value and the second the positive. Structure: `["false value", "true value"]`.
121
+ If not defined, it will default to *Yes* and *No* options.
122
+
123
+ ### Date
124
+
125
+ <%= best_in_place @user, :birth_date, :type => :date %>
126
+
127
+ With the :date type the input field will be initialized as a datepicker input.
128
+ In order to provide custom options to the datepicker initialization you must
129
+ prepare a `$.datepicker.setDefaults` call with the preferences of your choice.
130
+
131
+ More information about datepicker and setting defaults can be found
132
+ [here](http://docs.jquery.com/UI/Datepicker/$.datepicker.setDefaults)
133
+
134
+ ## Controller response with respond_with_bip
135
+
136
+ Best in place provides a utility method you should use in your controller in
137
+ order to provide the response that is expected by the javascript side, using
138
+ the :json format. This is a simple example showing an update action using it:
139
+
140
+ def update
141
+ @user = User.find params[:id]
142
+
143
+ respond_to do |format|
144
+ if @user.update_attributes(params[:user])
145
+ format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
146
+ format.json { respond_with_bip(@user) }
147
+ else
148
+ format.html { render :action => "edit" }
149
+ format.json { respond_with_bip(@user) }
150
+ end
151
+ end
152
+ end
153
+
154
+
155
+ ## Custom display methods
156
+
157
+ ### Using `display_as`
158
+
159
+ As of best in place 1.0.3 you can use custom methods in your model in order to
160
+ decide how a certain field has to be displayed. You can write something like:
161
+
162
+ = best_in_place @user, :description, :type => :textarea, :display_as => :mk_description
163
+
164
+ Then instead of using `@user.description` to show the actual value, best in
165
+ place will call `@user.mk_description`. This can be used for any kind of
166
+ custom formatting, text with markdown, etc...
167
+
168
+ ### Using `display_with`
169
+
170
+ In practice the most common situation is when you want to use an existing
171
+ helper to render the attribute, like `number_to_currency` or `simple_format`.
172
+ As of version 1.0.4 best in place provides this feature using the
173
+ `display_with` option. You can use it like this:
174
+
175
+ = best_in_place @user, :money, :display_with => :number_to_currency
176
+
177
+ If you want to pass further arguments to the helper you can do it providing an
178
+ additional `helper_options` hash:
179
+
180
+ = best_in_place @user, :money, :display_with => :number_to_currency, :helper_options => {:unit => "€"}
181
+
182
+ You can also pass in a proc or lambda like this:
183
+
184
+ = best_in_place @post, :body, :display_with => lambda { |v| textilize(v).html_safe }
185
+
186
+ ## Ajax success callback
187
+
188
+ ### Binding to ajax:success
189
+
190
+ The 'ajax:success' event is triggered upon success. Use bind:
191
+
192
+ $('.best_in_place').bind("ajax:success", function(){$(this).closest('tr').effect('highlight'));});
193
+
194
+ To bind a callback that is specific to a particular field, use the 'classes' option in the helper method and
195
+ then bind to that class.
196
+
197
+ <%= best_in_place @user, :name, :classes => 'highlight_on_success' %>
198
+ <%= best_in_place @user, :mail, :classes => 'bounce_on_success' %>
199
+
200
+ $('.highlight_on_success').bind("ajax:success", function(){$(this).closest('tr').effect('highlight'));});
201
+ $('.bounce_on_success').bind("ajax:success", function(){$(this).closest('tr').effect('bounce'));});
202
+
203
+ ### Providing data to the callback
204
+
205
+ Use the :data option to add HTML5 data attributes to the best_in_place span. For example, in your view:
206
+
207
+ <%= best_in_place @user, :name, :data => {:user_name => @user.name} %>
208
+
209
+ And in your javascript:
210
+
211
+ $('.best_in_place').bind("ajax:success", function(){ alert('Name updated for '+$(this).data('userName')); });
212
+
213
+ ##Non Active Record environments
214
+ We are not planning to support other ORMs apart from Active Record, at least for now. So, you can perfectly consider the following workaround as *the right way* until a specific implementation is done for your ORM.
215
+
216
+ Best In Place automatically assumes that Active Record is the ORM you are using. However, this might not be your case, as you might use another ORM (or not ORM at all for that case!). Good news for you: even in such situation Best In Place can be used!
217
+
218
+ Let's setup an example so we can illustrate how to use Best In Place too in a non-ORM case. Imagine you have an awesome ice cream shop, and you have a model representing a single type of ice cream. The IceCream model has a name, a description, a... nevermind. The thing is that it also has a stock, which is a combination of flavour and size. A big chocolate ice cream (yummy!), a small paella ice cream (...really?), and so on. Shall we see some code?
219
+
220
+ class IceCream < ActiveRecord::Base
221
+ serialize :stock, Hash
222
+
223
+ # consider the get_stock and set_stock methods are already defined
224
+ end
225
+
226
+ Imagine we want to have a grid showing all the combinations of flavour and size and, for each combination, an editable stock. Since the stock for a flavour and a size is not a single and complete model attribute, we cannot use Best In Place *directly*. But we can set it up with an easy workaround.
227
+
228
+ In the view, we'd do:
229
+
230
+ // @ice_cream is already available
231
+ - flavours = ... // get them somewhere
232
+ - sizes = ... // get them somewhere
233
+ %table
234
+ %tr
235
+ - ([""] + flavours).each do |flavour|
236
+ %th= flavour
237
+ - sizes.each do |size|
238
+ %tr
239
+ %th= size
240
+ - flavours.each do |flavour|
241
+ - v = @ice_cream.get_stock(:flavour => flavour, :size => size)
242
+ %td= best_in_place v, :to_i, :type => :input, :path => set_stock_ice_cream_path(:flavour => flavour, :size => size)
243
+
244
+ Now we need a route to which send the stock updates:
245
+
246
+ TheAwesomeIceCreamShop::Application.routes.draw do
247
+ ...
248
+
249
+ resources :ice_creams, :only => :none do
250
+ member do
251
+ put :set_stock
252
+ end
253
+ end
254
+
255
+ ...
256
+ end
257
+
258
+ And finally we need a controller:
259
+
260
+
261
+ class IceCreamsController < ApplicationController::Base
262
+ respond_to :html, :json
263
+
264
+ ...
265
+
266
+ def set_stock
267
+ flavour = params[:flavour]
268
+ size = params[:size]
269
+ new_stock = (params["fixnum"] || {})["to_i"]
270
+
271
+ @ice_cream.set_stock(new_stock, { :flavour => flavour, :size => size })
272
+ if @ice_cream.save
273
+ head :ok
274
+ else
275
+ render :json => @ice_cream.errors.full_messages, :status => :unprocessable_entity
276
+ end
277
+ end
278
+
279
+ ...
280
+
281
+ end
282
+
283
+ And this is how it is done!
284
+
285
+ ---
286
+
287
+ ##Test Helpers
288
+ Best In Place has also some helpers that may be very useful for integration testing. Since it might very common to test some views using Best In Place, some helpers are provided to ease it.
289
+
290
+ As of now, a total of four helpers are available. There is one for each of the following BIP types: a plain text input, a textarea, a boolean input and a selector. Its function is to simulate the user's action of filling such fields.
291
+
292
+ These four helpers are listed below:
293
+
294
+ * **bip_area(model, attr, new_value)**
295
+ * **bip_text(model, attr, new_value)**
296
+ * **bip_bool(model, attr)**
297
+ * **bip_select(model, attr, name)**
298
+
299
+ The parameters are defined here (some are method-specific):
300
+
301
+ * **model**: the model to which this action applies.
302
+ * **attr**: the attribute of the model to which this action applies.
303
+ * **new_value** (only **bip_area** and **bip_text**): the new value with which to fill the BIP field.
304
+ * **name** (only **bip_select**): the name to select from the dropdown selector.
305
+
306
+ ---
307
+
308
+ ##Installation
309
+
310
+ ###Rails 3.1 and higher
311
+
312
+ Installing *best_in_place* is very easy and straight-forward, even more
313
+ thanks to Rails 3.1. Just begin including the gem in your Gemfile:
314
+
315
+ gem "best_in_place"
316
+
317
+ After that, specify the use of the jquery and best in place
318
+ javascripts in your application.js, and optionally specify jquery-ui if
319
+ you want to use jQuery UI datepickers:
320
+
321
+ //= require jquery
322
+ //= require jquery-ui
323
+ //= require best_in_place
324
+
325
+ If you want to use jQuery UI datepickers, you should also install and
326
+ load your preferred jquery-ui CSS file and associated assets.
327
+
328
+ Then, just add a binding to prepare all best in place fields when the document is ready:
329
+
330
+ $(document).ready(function() {
331
+ /* Activating Best In Place */
332
+ jQuery(".best_in_place").best_in_place();
333
+ });
334
+
335
+ You are done!
336
+
337
+ ###Rails 3.0 and lower
338
+
339
+ Installing *best_in_place* for Rails 3.0 or below is a little bit
340
+ different, since the master branch is specifically updated for Rails
341
+ 3.1. But don't be scared, you'll be fine!
342
+
343
+ Rails 3.0 support will be held in the 0.2.X versions, but we have planned not to continue developing for this version of Rails. Nevertheless, you can by implementing what you want and sending us a pull request.
344
+
345
+ First, add the gem's 0.2 version in the Gemfile:
346
+
347
+ gem "best_in_place", "~> 0.2.0"
348
+
349
+ After that, install and load all the javascripts from the folder
350
+ **/public/javascripts** in your layouts. They have to be in the order:
351
+
352
+ * jquery
353
+ * **best_in_place**
354
+
355
+ You can automatize this installation by doing
356
+
357
+ rails g best_in_place:setup
358
+
359
+ If you want to use jQuery UI datepickers, you should also install and
360
+ load jquery-ui.js as well as your preferred jquery-ui CSS file and
361
+ associated assets.
362
+
363
+ Finally, as for Rails 3.1, just add a binding to prepare all best in place fields when the document is ready:
364
+
365
+ $(document).ready(function() {
366
+ /* Activating Best In Place */
367
+ jQuery(".best_in_place").best_in_place();
368
+ });
369
+
370
+ ---
371
+
372
+ ## Notification
373
+
374
+ Sometimes your in-place updates will fail due to validation or for some other reason. In such case, you'll want to notify the user somehow. **Best in Place** supports doing so through the best_in_place:error event, and has built-in support for notification via jquery.purr, right out of the box.
375
+
376
+ To opt into the jquery.purr error notification, just add best_in_place.purr to your javascripts, as described below. If you'd like to develop your own custom form of error notification, you can use best_in_place.purr as an example to guide you.
377
+
378
+ ###Rails 3.1 and higher
379
+
380
+ It's as simple as adding:
381
+
382
+ //= require best_in_place.purr
383
+
384
+ ###Rails 3.0 and lower
385
+
386
+ You'll have to load the following additional javascripts, in this order, after loading jquery and **best_in_place**:
387
+
388
+ * jquery.purr
389
+ * **best_in_place.purr**
390
+
391
+ ---
392
+
393
+ ## Security
394
+
395
+ If the script is used with the Rails Gem no html tags will be allowed unless the sanitize option is set to true, in that case only the tags [*b i u s a strong em p h1 h2 h3 h4 h5 ul li ol hr pre span img*] will be allowed. If the script is used without the gem and with frameworks other than Rails, then you should make sure you are providing the csrf authenticity params as meta tags and you should always escape undesired html tags such as script, object and so forth.
396
+
397
+ <meta name="csrf-param" content="authenticity_token"/>
398
+ <meta name="csrf-token" content="YOUR UNIQUE TOKEN HERE"/>
399
+
400
+ ---
401
+
402
+ ##TODO
403
+
404
+ - Client Side Validation definitions
405
+ - Accepting more than one handler to activate best_in_place fields
406
+
407
+ ---
408
+
409
+ ## Development
410
+
411
+ Fork the project on [github](https://github.com/bernat/best_in_place 'bernat / best_in_place on Github')
412
+
413
+ $ git clone <<your fork>
414
+ $ cd best_in_place
415
+ $ bundle
416
+
417
+ ### Prepare the test app
418
+
419
+ $ cd test_app
420
+ $ bundle
421
+ $ bundle exec rake db:test:prepare
422
+ $ cd ..
423
+
424
+ ### Run the specs
425
+
426
+ $ bundle exec rspec spec/
427
+
428
+ ### Bundler / gem troubleshooting
429
+
430
+ - make sure you've run the bundle command for both the app and test_app!
431
+ - run bundle update <<gem name> (in the right place) for any gems that are causing issues
432
+
433
+ ---
434
+
435
+ ##Authors, License and Stuff
436
+
437
+ Code by [Bernat Farrero](http://bernatfarrero.com) from [Itnig Web Services](http://itnig.net) (it was based on the [original project](http://github.com/janv/rest_in_place/) of Jan Varwig) and released under [MIT license](http://www.opensource.org/licenses/mit-license.php).
438
+
439
+ Many thanks to the contributors: [Roger Campos](http://github.com/rogercampos), [Jack Senechal](https://github.com/jacksenechal) and [Albert Bellonch](https://github.com/albertbellonch).