# Include code (conditionally) in a class and its subclasses

**URL:** <https://www.ruby-forum.com/t/include-code-conditionally-in-a-class-and-its-subclasses/151528>\
**Category:** Ruby\
**Created:** [October 22, 2008, 3:20pm UTC](https://www.ruby-forum.com/t/include-code-conditionally-in-a-class-and-its-subclasses/151528 "2008-10-22T15:20:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![alfredogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/dbc845/32.png) [@alfredogz](https://www.ruby-forum.com/u/alfredogz)\
**Post date:** [October 22, 2008, 3:20pm UTC](https://www.ruby-forum.com/t/include-code-conditionally-in-a-class-and-its-subclasses/151528/1 "2008-10-22T15:20:28Z")

</div>

Hi.  
Is there a way to include code in a class and all its subclasses and get  
the behaviour as if it was included at the end of the code in each of  
them?

Example:

class Product\<ActiveRecord::Base  
def price  
100  
end  
end

module ProductExtension  
def price  
120  
end  
end

I would wish find a way to include this module to the  
superclass(ActiveRecord::Base) and get the following result:

@product=Product.new  
@product.price =\>120

or even

module ProductExtension  
def precio  
old\_price+30  
end  
alias\_method :old\_price, :price  
alias\_method :price, :old\_price  
end

@product=Product.new  
@product.price =\>130

The module to include would be conditional.  
Ex: If the current class is Product I would include ProductExtension.  
If the current class is Category I would include CategoryExtension.

Perhaps thereÂ´s a better way to chieve this.Accept suggestions.  
Thanks for reading.

---

<div class="post-metadata">

**Author:** ![alfredogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/dbc845/32.png) [@alfredogz](https://www.ruby-forum.com/u/alfredogz)\
**Post date:** [October 22, 2008, 3:24pm UTC](https://www.ruby-forum.com/t/include-code-conditionally-in-a-class-and-its-subclasses/151528/2 "2008-10-22T15:24:54Z")

</div>

Sorry,this is wrong

> module ProductExtension  
> def precio  
> old\_price+30  
> end  
> alias\_method :old\_price, :price  
> alias\_method :price, :old\_price  
> end

It would be …

module ProductExtension  
def new\_price  
old\_price+30  
end  
alias\_method :old\_price, :price  
alias\_method :price, :new\_price  
end
