-
-
Save gerrywastaken/2c59bb5602e5a41b0dba to your computer and use it in GitHub Desktop.
This file contains 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
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