# Dynamic controller code

**URL:** <https://www.ruby-forum.com/t/dynamic-controller-code/140559>\
**Category:** Rails\
**Created:** [June 16, 2008, 9:17am UTC](https://www.ruby-forum.com/t/dynamic-controller-code/140559 "2008-06-16T09:17:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![indigoi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@indigoi](https://www.ruby-forum.com/u/indigoi)\
**Post date:** [June 16, 2008, 9:17am UTC](https://www.ruby-forum.com/t/dynamic-controller-code/140559/1 "2008-06-16T09:17:04Z")

</div>

is it possible to dynamically create controller code??

for example if you have a parent element @parent and children element  
@parent.daughter and @parent.son.

@parent.daughter.class = daughter  
@parent.son.class = son

so if we wanted to add a dog to all of our sons or all of our daughters  
when a controller element is called we would have to do something like  
this.

def dog  
if @child.class == son  
for son in @parent.sons  
son.dog = true  
son.save!  
end  
else  
for daughter in @parent.daughters  
daughter.dog = true  
daughter.save!  
end  
end  
end

Duplicating code like this is annoying and not very DRY is anything like  
this remotely possible instead ??

def dog  
child\_type = @child.class  
for child\_type in @parent.child\_type+s  
child\_type.dog = true  
child\_type.save!  
end  
end

this would cut code almost in half, for this situation. If there is  
anything capable of dynamically generating controller code based on  
object classes or even defined variables please let me know!!

---

<div class="post-metadata">

**Author:** ![indigoi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/b3f665/32.png) [@indigoi](https://www.ruby-forum.com/u/indigoi)\
**Post date:** [June 16, 2008, 9:41am UTC](https://www.ruby-forum.com/t/dynamic-controller-code/140559/2 "2008-06-16T09:41:48Z")

</div>

On Jun 16, 8:17 am, Richard S. \<rails-mailing-l…@andreas-  
[s.net](http://s.net)\> wrote:

> end

Well you could write something like this:

def set\_dog(association\_name)  
collection = @parent.send association\_name  
collection.each {|element| element.update\_attributes :dog =\> true}  
end

Although I’d have this as method on the parent class, rather than in  
the controller.
