Method: Puppet::Pops::Types::PObjectType#create_new_function

Defined in:
lib/puppet/pops/types/p_object_type.rb

#create_new_functionObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/puppet/pops/types/p_object_type.rb', line 504

def create_new_function
  impl_class = implementation_class
  return impl_class.create_new_function(self) if impl_class.respond_to?(:create_new_function)

  (param_names, param_types, required_param_count) = parameter_info(impl_class)

  # Create the callable with a size that reflects the required and optional parameters
  create_type = TypeFactory.callable(*param_types, required_param_count, param_names.size)
  from_hash_type = TypeFactory.callable(init_hash_type, 1, 1)

  # Create and return a #new_XXX function where the dispatchers are added programmatically.
  Puppet::Functions.create_loaded_function(:"new_#{name}", loader) do
    # The class that creates new instances must be available to the constructor methods
    # and is therefore declared as a variable and accessor on the class that represents
    # this added function.
    @impl_class = impl_class

    def self.impl_class
      @impl_class
    end

    # It's recommended that an implementor of an Object type provides the method #from_asserted_hash.
    # This method should accept a hash and assume that type assertion has been made already (it is made
    # by the dispatch added here).
    if impl_class.respond_to?(:from_asserted_hash)
      dispatcher.add(Functions::Dispatch.new(from_hash_type, :from_hash, ['hash']))
      def from_hash(hash)
        self.class.impl_class.from_asserted_hash(hash)
      end
    end

    # Add the dispatch that uses the standard #from_asserted_args or #new method on the class. It's assumed that the
    # method performs no assertions.
    dispatcher.add(Functions::Dispatch.new(create_type, :create, param_names))
    if impl_class.respond_to?(:from_asserted_args)
      def create(*args)
        self.class.impl_class.from_asserted_args(*args)
      end
    else
      def create(*args)
        self.class.impl_class.new(*args)
      end
    end
  end
end