Skip to content

Instantly share code, notes, and snippets.

@bibstha
Created June 16, 2015 07:45
Show Gist options
  • Save bibstha/1e74bd137e13a313b5fd to your computer and use it in GitHub Desktop.
Save bibstha/1e74bd137e13a313b5fd to your computer and use it in GitHub Desktop.
module Quackable
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def has_voice(word)
@words ||= []
@words << word
end
end
def quack
self.class.instance_variable_get("@words").each { |w| puts "#{self.class} says #{w}" }
end
end
class Dog
include Quackable
has_voice :bow
has_voice :wow
end
class Duck
include Quackable
has_voice :quack
has_voice :qwwack
end
class BullTerrier < Dog
has_voice :growl
end
Dog.new.quack
Duck.new.quack
Dog.new.quack
Duck.new.quack
BullTerrier.new.quack
# Cannot use @@variables because then it will be shared with all
# Solution is to use class_attribute
# http://apidock.com/rails/Class/class_attribute
puts "======="
require 'active_support'
require 'active_support/core_ext/class/attribute'
module Quackable2
def self.included(base)
base.class_eval do
base.extend ClassMethods
class_attribute :words
self.words = []
end
end
module ClassMethods
def has_voice2(word)
self.words += [word]
end
end
def quack2
self.class.words.each { |w| puts "#{self.class} says #{w}" }
end
end
class Dog
include Quackable2
has_voice2 :bow
has_voice2 :wow
end
class BullTerrier
has_voice2 :growl
end
Dog.new.quack2
BullTerrier.new.quack2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment