Skip to content

Commit

Permalink
improve JSON parsing by using model name and field name instead of ju…
Browse files Browse the repository at this point in the history
…st guessing
  • Loading branch information
nakajima committed Aug 7, 2008
1 parent ce88e71 commit ee78a13
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 8 deletions.
15 changes: 8 additions & 7 deletions src/editable.js
Expand Up @@ -20,9 +20,10 @@ var Editable = Class.create({
// If you want to edit the "comment_body" field in a "MemberBlogPost" model,
// it would be: "member_blog_post_#{@member_blog_post.id}_comment_body"
parseField: function() {
var matches = this.elementID.match(/(.*)_(\d*)_(.*)/);
var fieldString = matches[1] + '[' + matches[3] + ']';
return fieldString;
var matches = this.elementID.match(/(.*)_\d*_(.*)/);
this.modelName = matches[1];
this.fieldName = matches[2];
return this.modelName + '[' + this.fieldName + ']';
},

// Create the editing form for the editable and inserts it after the element.
Expand Down Expand Up @@ -75,10 +76,10 @@ var Editable = Class.create({
parameters: pars,
onSuccess: function(transport) {
var json = transport.responseText.evalJSON();
var attr = this.field.replace(/\w+\[(\w+)\]/, '$1');
this.value = json[attr];
this.editInput.value = json[attr];
this.element.update(json[attr]);
if (json[this.modelName]) { this.value = json[this.modelName][this.fieldName]; }
else { this.value = json[this.fieldName]; }
this.editInput.value = this.value;
this.element.update(this.value);
form.enable();
this.cancel();
}.bind(this),
Expand Down
2 changes: 1 addition & 1 deletion test/lib/test_server.rb
Expand Up @@ -19,6 +19,6 @@
end

put '/users/2' do
user = { :first_name => params['user[first_name]'] }
user = { :user => { :first_name => params['user[first_name]'] } }
user.to_json
end
4 changes: 4 additions & 0 deletions test/unit/editable_test.html
Expand Up @@ -40,6 +40,10 @@ <h1>Better Edit in Place test file</h1>
testParseForFieldName: function() {
this.assertEqual('list[title]', this.list.parseField());
this.assertEqual('user[first_name]', this.user.parseField());
this.assertEqual('list', this.list.modelName);
this.assertEqual('title', this.list.fieldName);
this.assertEqual('user', this.user.modelName);
this.assertEqual('first_name', this.user.fieldName);
},

testShouldGetValue: function() {
Expand Down

0 comments on commit ee78a13

Please sign in to comment.