Created
August 9, 2015 14:41
Code for blog post http://jpmoral.com/ruby/2015/08/09/metaprogramming-class-instance-variables-and-inheritance.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Echoer | |
def echoes(*phrases) | |
@known_phrases.concat(phrases) | |
@known_phrases.each do |phrase| | |
next if self.respond_to?(phrase.to_sym) | |
define_method("#{phrase}") { phrase.to_s } | |
end | |
end | |
def known_phrases | |
@known_phrases.map do |phrase| | |
phrase.to_s | |
end | |
end | |
def self.extended(mod) | |
mod.instance_variable_set(:@known_phrases, []) | |
mod.send :include, InstanceMethods | |
end | |
def inherited(subclass) | |
subclass.instance_variable_set(:@known_phrases, @known_phrases) | |
end | |
module InstanceMethods | |
def echo(phrase) | |
phrase.to_s | |
end | |
def known_phrases | |
self.class.known_phrases | |
end | |
end | |
end | |
class Person | |
extend Echoer | |
echoes :hello, :goodbye | |
end | |
class Shopper < Person | |
echoes :charge | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment