Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require "delegate"
class CollectionProxy
def products
@products ||= HasManyAssociation.new([])
@products.associated_class ||= Product
@products
end
end
class Product
def initialize(attributes)
@attributes = attributes
end
attr_reader :attributes
def name
attributes[:name]
end
end
# -----------------------------------------------------------
# With DelegateClass
# -----------------------------------------------------------
class HasManyAssociation < DelegateClass(Array)
attr_accessor :associated_class
def initialize(array)
super(array)
end
def create(params)
self << associated_class.new(params)
end
end
proxy = CollectionProxy.new
products = proxy.products
products.create(:name => 'products one')
products.create(:name => 'products two')
p products[0].name
p products[1].name
p products.map { |q| q.name }
# -----------------------------------------------------------
# with method_missing
# -----------------------------------------------------------
class HasManyAssociation < BasicObject
attr_accessor :associated_class
def initialize(array)
@array = array
end
def create(params)
self << associated_class.new(params)
end
def method_missing(*a, &b)
@array.send(*a, &b)
end
end
proxy = CollectionProxy.new
products = proxy.products
products.create(:name => 'products one')
products.create(:name => 'products two')
p products.map { |q| q.name }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.