Skip to content

Instantly share code, notes, and snippets.

@zampino
Created December 17, 2012 10:12
Show Gist options
  • Save zampino/4317238 to your computer and use it in GitHub Desktop.
Save zampino/4317238 to your computer and use it in GitHub Desktop.
struct draft
require 'active_support/core_ext'
require 'ostruct'
# require 'debugger'
module Factory
PRIMARY_KEY_NAME = "name"
def self.build(node, content, options={})
Factory.for(node, content, options).produce
node
end
def self.for(node, content, options)
unless factory_name = options[:with_factory]
# naive respond to chose
factory_name = {
each_pair: 'dictionary',
each: 'collection',
object_id: 'simple'
}.detect { |method, name|
content.respond_to?(method)
}[1]
end
factory_class = Factory.const_get factory_name.classify
factory_class.new(node, content, options)
end
end
class Factory::Base
def initialize(node, content, options={ })
puts 'init Factory', self.class
@node = node
@content = content
end
def produce
puts 'reproducing node'
apply &procedure
end
def apply
raise NotImplemented
end
def procedure
raise NotImplemented
end
class NotImplemented < StandardError; end
end
class Factory::Collection < Factory::Base
def apply &block
@content.each.with_index &block
end
def procedure
proc { |item, index|
#id = "#{@node.id}/#{index}"
child = @node.create_child
Factory.build(child, item)
}
end
end
class Factory::Dictionary < Factory::Collection
def procedure
proc { |(key, value), index|
# id, value = *id_value
id, options = *primary_key_from(key)
child = @node.create_child(id)
Factory.build(child, value, options)
}
end
def primary_key_from(key)
data = key.split(" ")
id = data.shift
options = { }
unless data.empty?
data.each.with_object(options) { |query, memo|
key, value = query.split("=")
memo[key] = value
}[:with_fatcory]= "named_collection"
end
[id, options]
end
end
class Factory::NamedCollection < Factory::Collection
def initialize(node, content, options)
@name = options[PRIMARY_KEY_NAME]
super(node, content)
end
def procedure
proc { |object, index|
id = object[@name]
child = @node.create_child(id)
Factory.build(child, object)
}
end
end
class Factory::Simple < Factory::Base
def apply
yield
end
def procedure
proc {
puts 'assigning value to node'
@node.value= @content
}
end
end
class Node < OpenStruct
attr_reader :id
attr :parent, :value
def initialize(id=nil, attrs = {})
@id = id
super(attrs)
end
def inspectx
"<#{id} parent=#{parent.inspect} value=#{value}>"
end
def children
@children ||= []
end
def create_child(id=nil, attrs = {})
n = Node.new(id)
n.parent = self
children << n
n
end
end
content = {"foo" => { mar: "mal", tant: "ar" }, rob: "aaaa" }.with_indifferent_access
root = Node.new("root")
root.children
root = Factory.build(root, content)
ObjectSpace.each_object(Factory::Base) { |o| puts o }
c = root.children
c.first.children
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment