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

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

#create_new_function(loader) ⇒ Object

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.



431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/puppet/pops/types/p_object_type.rb', line 431

def create_new_function(loader)
  impl_class = implementation_class
  class_name = impl_class.name || "Anonymous Ruby class for #{name}"

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

  # Create the callable with a size that reflects the required and optional parameters
  param_types << required_param_count
  param_types << param_names.size

  create_type = TypeFactory.callable(*param_types)
  from_hash_type = TypeFactory.callable(i12n_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