Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerrywastaken/2c59bb5602e5a41b0dba to your computer and use it in GitHub Desktop.
Save gerrywastaken/2c59bb5602e5a41b0dba to your computer and use it in GitHub Desktop.
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