Sha256: c938dc930314f74e4346bf535b0364a340f0d19e1236858c814584b53ca69711

Contents?: true

Size: 1.82 KB

Versions: 3

Compression:

Stored size: 1.82 KB

Contents

require 'travis/client'

module Travis
  module Client
    class Namespace < Module
      class Curry < Module
        attr_accessor :namespace, :type

        def initialize(namespace, type)
          @namespace, @type = namespace, type
        end

        def find_one(id = nil)
          result = session.find_one(type, id)
          result.curry = self
          result
        end

        def current
          result = session.find_one_or_many(type)
          Array(result).each { |e| e.curry = self }
          result
        end

        def find_many(params = {})
          session.find_many(type, params).each do |entity|
            entity.curry = self
          end
        end

        alias find     find_one
        alias find_all find_many

        private

          def session
            namespace.session
          end
      end

      include Methods
      attr_accessor :session

      def initialize(session = nil)
        session  = Travis::Client.new(session || {}) unless session.is_a? Session
        @session = session

        Entity.subclasses.each do |subclass|
          name = subclass.name[/[^:]+$/]
          const_set(name, Curry.new(self, subclass))
        end
      end

      def included(klass)
        fix_names(klass)
        delegate_session(klass)
      end

      private

        def fix_names(klass)
          constants.each do |name|
            const = klass.const_get(name)
            klass.const_set(name, const) if const == const_get(name)
          end
        end

        def delegate_session(klass)
          return if klass == Object or klass == Kernel
          klass.extend(Methods)
          namespace = self
          klass.define_singleton_method(:session)  { namespace.session }
          klass.define_singleton_method(:session=) { |value| namespace.session = value }
        end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
travis-1.2.2 lib/travis/client/namespace.rb
travis-1.2.1 lib/travis/client/namespace.rb
travis-1.2.0 lib/travis/client/namespace.rb