forked from ryanb/nested_form
-
Notifications
You must be signed in to change notification settings - Fork 1
/
install.rb
executable file
·52 lines (46 loc) · 1.77 KB
/
install.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
path = "public/javascripts/nested_form.js"
puts "Generating #{path}"
File.open("#{Rails.root}/#{path}", "w") do |file|
file.print <<-EOS
$(function() {
$('form a.add_nested_fields').live('click', function() {
// Setup
var assoc = $(this).attr('data-association'); // Name of child
var content = $('#' + assoc + '_fields_blueprint').html(); // Fields template
// Make the context correct by replacing new_<parents> with the generated ID
// of each of the parent objects
var context = ($(this).parents('.fields').children('input:first').attr('name') || '').replace(new RegExp('\[[a-z]+\]$'), '');
// context will be something like this for a brand new form:
// project[tasks_attributes][1255929127459][assignments_attributes][1255929128105]
// or for an edit form:
// project[tasks_attributes][0][assignments_attributes][1]
if(context) {
var parent_names = context.match(/[a-z]+_attributes/g) || []
var parent_ids = context.match(/[0-9]+/g)
for(i = 0; i < parent_names.length; i++) {
if(parent_ids[i]) {
content = content.replace(
new RegExp('(\\[' + parent_names[i] + '\\])\\[.+?\\]', 'g'),
'$1[' + parent_ids[i] + ']'
)
}
}
}
// Make a unique ID for the new child
var regexp = new RegExp('new_' + assoc, 'g');
var new_id = new Date().getTime();
content = content.replace(regexp, new_id)
$(this).parent().before(content);
return false;
});
$('form a.remove_nested_fields').live('click', function() {
var hidden_field = $(this).prev('input[type=hidden]')[0];
if(hidden_field) {
hidden_field.value = '1';
}
$(this).closest('.fields').hide();
return false;
});
});
EOS
end