6b5a68d41436ce28831a0e0ca6bcd124

I've got a bunch of add and remove functions that would be nice to refactor without all the duplication. Lets see what you can do! Thanks!

Helper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  def add_phone_link(name)
    link_to_function "Add another" do |page|
    	page.insert_html :bottom, :phones, :partial => 'phone', :object => Phone.new
    end
  end
  
  def remove_phone_link(name)
    link_to_function "Remove" do |page|
      page["phone_#{params[:index]}"].remove
    end
  end
  
  def add_email_link(name)
    link_to_function "Add another" do |page|
    	page.insert_html :bottom, :emails, :partial => 'email', :object => Email.new
    end
  end
  
  def remove_email_link(name)
    link_to_function "Remove" do |page|
      page["email_#{params[:index]}"].remove
    end
  end

Refactorings

No refactoring yet !

D16d53391068ff0830269149b060789d

Jason Dew

October 16, 2007, October 16, 2007 23:25, permalink

1 rating. Login to rate!

I don't see where you use the argument to these functions.... Anyway, here's my shot at refactoring

1
2
3
4
5
6
7
8
9
  def add_associated_link(model_name, label = "Add another")
    link_to_function label do |page|
    	page.insert_html :bottom, model_name.pluralize, :partial => model_name, :object => model_name.camelize.constantize.new
    end
  end
  
  def remove_associated_link(model_name, label = "Remove")
    link_to_function label {|page| page["#{model_name}_#{params[:index]}"].remove }
  end
6b5a68d41436ce28831a0e0ca6bcd124

Etandrib

October 17, 2007, October 17, 2007 20:50, permalink

No rating. Login to rate!

Here is where I call the links. For some reason I get an error with the new code saying the following:
Showing app/views/people/_fields.rhtml where line #11 raised: "Add another" is not a valid constant name!"

_fields

1
2
3
4
<h3>Phone Numbers</h3>
  <%= render :partial => 'phone', :collection => @person.phones %>
<%= add_associated_link "Add another" %>
991b8de70c5edb062ddfe8cd9b59277e

namxam

October 17, 2007, October 17, 2007 21:02, permalink

1 rating. Login to rate!

If you look a little bit closer, you will see, that the first param to Jason's refactored code is the model name, so your call is wrong.

1
<%= add_associated_link 'Email', "Add another" %>
6b5a68d41436ce28831a0e0ca6bcd124

Etandrib

October 17, 2007, October 17, 2007 21:06, permalink

No rating. Login to rate!

Ah, ok. I see now. Thanks!

Your refactoring





Format Copy from initial code

or Cancel