# DRY respond\_to

**URL:** <https://www.ruby-forum.com/t/dry-respond-to/73768>\
**Category:** Rails\
**Created:** [October 26, 2006, 10:43pm UTC](https://www.ruby-forum.com/t/dry-respond-to/73768 "2006-10-26T22:43:03Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![W\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/aca169/32.png) [@W\_S](https://www.ruby-forum.com/u/W_S)\
**Post date:** [October 26, 2006, 10:43pm UTC](https://www.ruby-forum.com/t/dry-respond-to/73768/1 "2006-10-26T22:43:03Z")

</div>

Here is how my restful new action look like:

def new  
@foo = @widget.build(params[:foo])  
raise NoPost unless request.post?  
@foo.save!  
respond\_to do |type|  
type.html { redirect\_to foo\_url }  
type.js { render :action =\> :create }  
end  
rescue NoPost  
respond\_to do |type|  
type.html { render :action =\> :new }  
type.js { render :partial =\> ‘form’ }  
end  
rescue ActiveRecord::RecordInvalid  
respond\_to do |type|  
type.html { render :action =\> :new }  
type.js { render :action =\> :create }  
end  
end  
alias :create :new

Any ideas how to DRY it?

---

<div class="post-metadata">

**Author:** ![W\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/aca169/32.png) [@W\_S](https://www.ruby-forum.com/u/W_S)\
**Post date:** [October 28, 2006, 5:47pm UTC](https://www.ruby-forum.com/t/dry-respond-to/73768/2 "2006-10-28T17:47:33Z")

</div>

rescue NoPost, ActiveRecord::RecordInvalid ?

---

<div class="post-metadata">

**Author:** ![W\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/aca169/32.png) [@W\_S](https://www.ruby-forum.com/u/W_S)\
**Post date:** [October 30, 2006, 2:16pm UTC](https://www.ruby-forum.com/t/dry-respond-to/73768/3 "2006-10-30T14:16:16Z")

</div>

Vishnu G. wrote:

> rescue NoPost, ActiveRecord::RecordInvalid ?

But those 2 rescues are different

---

<div class="post-metadata">

**Author:** ![W\_S](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/aca169/32.png) [@W\_S](https://www.ruby-forum.com/u/W_S)\
**Post date:** [November 7, 2006, 10:52am UTC](https://www.ruby-forum.com/t/dry-respond-to/73768/4 "2006-11-07T10:52:11Z")

</div>

Ah sorry, didn’t notice. There’s not much to DRY tho in that case. Try  
this:

rescue NoPost, ActiveRecord::RecordInvalid  
[…]  
type.js { render :action =\> ($!.is\_a? NoPost) ? :new : :create }

Just typing this out, but some variation of that will work.

Vish
