# How would you refactor this to make it more DRY

**URL:** <https://www.ruby-forum.com/t/how-would-you-refactor-this-to-make-it-more-dry/153458>\
**Category:** Rails\
**Created:** [November 17, 2008, 3:20pm UTC](https://www.ruby-forum.com/t/how-would-you-refactor-this-to-make-it-more-dry/153458 "2008-11-17T15:20:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [November 17, 2008, 3:20pm UTC](https://www.ruby-forum.com/t/how-would-you-refactor-this-to-make-it-more-dry/153458/1 "2008-11-17T15:20:19Z")

</div>

i have your typical nested resource pattern, and at most any resource  
is one level deep… so for a model PurchaseOrder which is optionally  
nested under Customer ive worked up this before\_filter…

but the problem is, i have my parent class name hard coded into the  
function… so i can either copy this to every controller (which i  
really know in my heart cant be appropriate) or ask for some input…

now i know all about resource\_controller and the make\_resourceful  
plugins… but they’re all a bit too magical and over the top for my  
needs - as awesome as they may be.

anyhow… heres the function.

private  
def load\_parent  
class\_name = :customer  
parent\_sym = “#{class\_name.to\_s}\_id”.to\_sym  
parent\_class = class\_name.to\_s.classify.constantize

```
# if there is a customer_id in params then load it...
#if not return the current controllers class, constantized so i

```

can do things like  
# @purchase\_order = @parent.find(params[:id])  
# in my actions and have it work regardless of the presence of a  
parent or not.

```
@parent = params[parent_sym] ?
  parent_class.find(params[parent_sym]).send

```

(self.controller\_name.tableize.to\_sym) :  
self.controller\_name.classify.constantize  
end
