Skip to content

Instantly share code, notes, and snippets.

@doubiz
Created February 3, 2016 21:30
Show Gist options
  • Select an option

  • Save doubiz/f88879bb3dced8af068a to your computer and use it in GitHub Desktop.

Select an option

Save doubiz/f88879bb3dced8af068a to your computer and use it in GitHub Desktop.

Revisions

  1. doubiz created this gist Feb 3, 2016.
    106 changes: 106 additions & 0 deletions example of Ruby meta-programming
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,106 @@
    module Animal

    def teach_all(technique, &block)
    puts "Teaching All #{self.name} the command #{technique}"
    define_method technique, block
    end

    def unteach_all(technique)
    puts "Teaching All #{self.name} the command #{technique}"
    remove_method technique
    end

    end




    class Dog
    extend Animal

    attr_accessor :name, :type
    def initialize(name)
    @name = name
    puts "Whooof!! Whooof!! this is #{name} I'm your #{type} dog please teach me!"
    end

    def teach(technique, command)
    puts "Teaching #{self.name} the command #{technique}"
    instance_eval <<-EOS, __FILE__, __LINE__ +1
    def #{technique}
    puts "#{command.call("#{technique}",self.name)}"
    end
    EOS
    end

    def unteach(technique)
    puts "Master I'm #{self.name} I'm losing my #{technique} technique"
    instance_eval <<-EOS, __FILE__, __LINE__ +1
    undef #{technique}
    EOS
    end


    def method_missing(m, *args, &blck)
    puts "#{m} #{self.name}"
    puts " I don't know how to #{m} please teach me!"
    end

    end

    #Specific types of

    class GoldenRetriever < Dog

    def initialize(name)
    @type = "golden"
    super(name)
    end

    end

    class German < Dog
    def initialize(name)
    @type = "german"
    super(name)
    end
    end

    class Rotwieler < Dog
    def initialize(name)
    @type = "rot"
    super(name)
    end
    end




    ## Main method
    bella = GoldenRetriever.new("bella")
    ceaser = German.new("ceaser")
    viky = GoldenRetriever.new("viky")


    command = lambda{ |technique, name| technique + " " + name + "\n Whoooffff! I can #{technique}"}

    #teaching all golden retrievers
    teach_all_commands = ["sit", "fetch"]
    teach_all_commands.each do |cmd|
    GoldenRetriever.teach_all(cmd) do puts "#{cmd} " + self.name + "\n Whoooffff! I can #{cmd}" end
    end
    #teach specific dogs
    bella.teach("stay", command)
    ceaser.teach("stay", command)

    bella.sit
    bella.stay
    bella.fetch

    ceaser.sit
    ceaser.stay
    ceaser.fetch

    viky.sit
    viky.stay
    viky.fetch