class Object
def mixin(m)
include m
@@modules ||= []
@@modules << m
end
def init_mods()
@@modules.each {|m| m.init(self)} if @@modules
end
def c_eval(s)
self.class.instance_eval(s)
end
def i_eval(s)
self.instance_eval(s)
end
end
module Carries
def self.init(base)
base.c_eval "attr_accessor :inventory"
base.i_eval "@inventory = Inventory.new"
end
end
class Inventory
def add(o)
puts "you have added a #{o} to your inventory!"
end
end
# ——————————————————
# Now all you have to write is:
class John
mixin Carries
def initialize()
init_mods()
end
end
j = John.new
j.inventory.add "Blade of Gondor"
#=> you have added a Blade of Gondor to your inventory!
class Inventory
def initialize(s)
add_item(s)
end
def add_item(i)
puts "you have added a #{i} to your inventory."
end
end
module Carries
attr_accessor :inventory
def initialize
@inventory = Inventory.new("Blade of Gondor")
end
end
class Player; include Carries; end
p = Player.new
puts p.inventory
#OUTPUT:
# => you have added a Blade of Gondor to your inventory.
# => #<Inventory:0x7fd42d88>
module Carries
def inventory
@inventory||=Inventory.new("Blade of Gondor")
end
end
module Boss
def initialize
puts "so boss!"
super
end
end
module Pal
def initialize
puts "whats up pal?"
super
end
end
class Friend; include Boss; include Pal; end
f = Friend.new
#=> whats up pal?
#=> so boss!
module M
attr :is_fine
end
# this resides in the run script polaris.rb
$imports = {}
def import(*files)
for f in files
if $imports[f]
require($imports[f])
else
raise "Import Error: #{f}.rb does not exist."
end
end
end
rb = File.join("**", "*.rb")
files = Dir.glob(rb)
files.each {|f| $imports[File.basename(f, ".rb").to_sym] = f}
$imports.each do |k,v|
next if k == :polaris
require(v)
puts "loaded #{k} -> #{v}"
end
# Example OUTPUT
#loaded character -> lib/core/base/character.rb
#loaded obtains -> lib/core/base/modules/obtains.rb
# in mobile.rb
import :character, :obtains
class Mobile < Character
include Obtains
end