require 'active_support' module TicketingHub class Collection include Enumerable def self.from_association parent, child_class, options={} path = [ parent.model_name.route_key, parent.id, child_class.model_name.route_key ].join '/' new path, parent, child_class end attr_accessor :elements, :parent, :child_class def initialize(elements, parent, child_class) self.elements = elements self.parent = parent self.child_class = child_class end def to_a elements.dup end def elements unless @elements.is_a? Array @elements = parent.client.get(path, options) .map { |attrs| child_class.new attrs, parent.client } end @elements end def method_missing(method, *args, &block) return super unless [].respond_to? method elements.send method, *args, &block end def build(attributes = {}) child_class.new.tap do |resource| { parent.foreign_key => parent.id, parent.model_name.singular_route_key => parent }.merge(attributes).each do |key, value| resource.send "#{key}=", value if resource.respond_to? "#{key}=" end end end def create(*args) build.create *args end end end