Include code (conditionally) in a class and its subclasses

  • Thread starter Alfredo Garcia lopez
  • Start date
A

Alfredo Garcia lopez

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 :eek:ld_price, :price
alias_method :price, :eek:ld_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.
 
A

Alfredo Garcia lopez

Sorry,this is wrong
module ProductExtension
def precio
old_price+30
end
alias_method :eek:ld_price, :price
alias_method :price, :eek:ld_price
end

It would be ...

module ProductExtension
def new_price
old_price+30
end
alias_method :eek:ld_price, :price
alias_method :price, :new_price
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top