Created
October 7, 2013 14:22
-
-
Save hpvb/6868823 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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