Skip to content

Instantly share code, notes, and snippets.

@hpvb
Created October 7, 2013 14:22
Show Gist options
  • Save hpvb/6868823 to your computer and use it in GitHub Desktop.
Save hpvb/6868823 to your computer and use it in GitHub Desktop.
class Factory
attr_reader :username
def initialize(args = {})
@username = args.fetch :username
end
def self.register_class(classname)
Factory.send :define_method, "#{classname.to_s.downcase}_by_name".to_sym do |args|
classname.new({ :username => self.username}.merge args)
end
end
module Constructable
def self.included(base)
Factory::register_class(base)
end
end
end
module Base
attr_accessor :username
def initialize(args = {})
self.username = args.fetch :username
self.mandatory_attributes.each do |attribute_name, attribute_value|
raise ArgumentError, "Mandatory attribute #{attribute_name} missing in initialization" if not args.has_key?(attribute_name)
define_attr(attribute_name)
self.send("#{attribute_name}=", args[attribute_name])
end
end
def define_attr(sym, val = nil)
singleton = class << self; self end
singleton.send :define_method, "#{sym}=".to_sym do |val|
self.instance_variable_set("@#{sym}", val)
end
singleton.send :define_method, sym.to_sym do
self.instance_variable_get("@#{sym}")
end
end
end
class Host
include Base
include Factory::Constructable
def mandatory_attributes
[ :name, ]
end
end
factory = Factory.new(:username => "lama")
host = factory.host_by_name(:name => "lama_by_name")
p host.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment