Forum: Ruby Include code (conditionally) in a class and its subclasses

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Alfredo G. (Guest)
on 2008-10-22 17:20
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.
Alfredo G. (Guest)
on 2008-10-22 17:24
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
This topic is locked and can not be replied to.