Meta Programming in rails

31 Views Asked by At

I have a class by name Person the methods are being added into name,description,nick_name but these instance methods do have the same set of code

class Product
  def name
    p "this is the name of the product"
  end

  def description
    p "this is the descriptions of the product"
  end

  def nick_name
    p "this si the description of the nick name"
  end
end

class Person < Product
  %w(name description nick_name).map{|attr| attr.to_sym}.each do |definable_method|
    define_method definable_method do
      print "this is the #{definable_method} in the person"
      super
    end
  end  
end
 p1 = Person.new
 p1.name

Expected Result

 this is the name in the person
 this is the name of product
p1.description

Expected Result

  this is description in the person
  this is the descriptions of product

1

There are 1 best solutions below

0
Rosel Sosa Gonzalez On

Try with this code

class Product
  def name
    p "this is the name of the product"
  end

  def description
    p "this is the descriptions of the product"
  end

  def nick_name
    p "this si the description of the nick name"
  end
end

class Person < Product
  %w(name description nick_name).map{|attr| attr.to_sym}.each do |definable_method|
    define_method definable_method do
      print "this is the #{definable_method} in the person\n"
      super()
    end
  end
end

p1 = Person.new
p1.name