Sha256: a25c04cd1a535725b85798dfcebb5b489223c3a0e3ef5c2efdbc7e3d649d2b74

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

module MongoMapper
  module Associations
    class Proxy
      attr_reader :owner, :association

      instance_methods.each do |m|
        undef_method m unless m =~ /(^__|^nil\?$|^send$|proxy_|^object_id$)/
      end

      def initialize(owner, association)
        @owner= owner
        @association = association

        reset
      end

      def respond_to?(*methods)
        (load_target && @target.respond_to?(*methods))
      end

      def reset
        @target = nil
      end

      def reload_target
        reset
        load_target
        self
      end

      def send(method, *args)
        load_target
        @target.send(method, *args)
      end

      def replace(v)
        raise NotImplementedError
      end

      protected
        def method_missing(method, *args)
          if load_target
            if block_given?
              @target.send(method, *args)  { |*block_args| yield(*block_args) }
            else
              @target.send(method, *args)
            end
          end
        end

        def load_target
          @target ||= find_target
        end

        def find_target
          raise NotImplementedError
        end
        
        # Array#flatten has problems with recursive arrays. Going one level
        # deeper solves the majority of the problems.
        def flatten_deeper(array)
          array.collect { |element| (element.respond_to?(:flatten) && !element.is_a?(Hash)) ? element.flatten : element }.flatten
        end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fcoury-mongomapper-0.2.0 lib/mongomapper/associations/proxy.rb