Sha256: 390aaa76d25bb64078de19a891b653f548346c1f5d5fc9165d590f10e37ec2f8

Contents?: true

Size: 1.27 KB

Versions: 1

Compression:

Stored size: 1.27 KB

Contents

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ticketinghub-0.0.2 lib/ticketing_hub/collection.rb