I have developed a back-end in Rails 3.2 that allows admins to perform CRUD operations using ajax and jQuery. I have done this with several controller/views using js.coffee files to handle the ajax. an example of my file structure for my views is as follows.
views
users
index.html.erb
_form.html.erb
_edit_form.html.erb
_user.html.erb
create.js.coffee
edit.js.coffee
update.js.coffee
destroy.js.coffee
customers
index.html.erb
_form.html.erb
_edit_form.html.erb
_customer.html.erb
create.js.coffee
edit.js.coffee
update.js.coffee
destroy.js.coffee
email_blasts
index.html.erb
_form.html.erb
_edit_form.html.erb
_blast.html.erb
create.js.coffee
edit.js.coffee
update.js.coffee
destroy.js.coffee
.
.
.
.
An example create.js.coffee for both the User views and Customer views is below. Notice the instance variables and div names that follow an exact pattern. All coffeescript below follows the exact structure in all the views that I have listed above. All create.js.coffee files listed above are virtually identical. My question is what’s the best way to reduce the duplication? Would this be something that I should create a plugin for? Should I put it in a helper…etc. I’m not sure how to handle this in rails as I am a former php programmer 🙁 Anyones help would be appreciated!
create.js.coffee for the User views:
$('#errors').empty()
$('#errors').show()
<% if @user.errors.any? %>
$('<%= escape_javascript(render :partial => "errors", :locals => {:target => @user })%>')
.appendTo('#errors')
<% else %>
$('<%= escape_javascript(render(:partial => @user))%>')
.appendTo('#user_table')
.hide()
.fadeIn(200)
$('#errors').hide()
$('#new_user')[0].reset()
$('#users_count').html '<%= users_count %>'
<% end %>
$('#error_close').click ->
$('#errors').fadeOut()
create.js.coffee for the Customer view
$('#errors').empty()
$('#errors').show()
<% if @customer.errors.any? %>
$('<%= escape_javascript(render :partial => "errors", :locals => {:target => @customer })%>')
.appendTo('#errors')
<% else %>
$('<%= escape_javascript(render(:partial => @customer))%>')
.appendTo('#customer_table')
.hide()
.fadeIn(200)
$('#errors').hide()
$('#new_customer')[0].reset()
$('#customers_count').html '<%= customers_count %>'
<% end %>
$('#error_close').click ->
$('#errors').fadeOut()
You should structure your code and if you want to reuse it stop mixing javascript and erb. Make JavaScript classes which do the job and put the data in side a script tag in the page…
Try to use some framework which helps you by giving structure like Backbone.js.
This could be useful to you:
Or the messy way: