Sha256: 882ce633e44ca34f8be29d65bae6cd1c2cebed71f85e3dab0d9a4e2a0a3ee704

Contents?: true

Size: 1.05 KB

Versions: 2

Compression:

Stored size: 1.05 KB

Contents

module Dry::Initializer::Builders
  # @private
  class Reader
    def self.[](definition)
      new(definition).call
    end

    def call
      lines.flatten.compact.join("\n")
    end

    private

    def initialize(definition)
      @target = definition.target
      @ivar   = definition.ivar
      @null   = definition.null
      @reader = definition.reader
    end

    def lines
      [undef_line, attribute_line, method_lines, type_line]
    end

    def undef_line
      "undef :#{@target} if method_defined?(:#{@target})" \
      "  || private_method_defined?(:#{@target})" \
      "  || protected_method_defined?(:#{@target})"
    end

    def attribute_line
      return unless @reader

      "attr_reader :#{@target}" unless @null
    end

    def method_lines
      return unless @reader
      return unless @null

      [
        "def #{@target}",
        "  #{@ivar} unless Dry::Initializer::UNDEFINED == #{@ivar}",
        'end'
      ]
    end

    def type_line
      "#{@reader} :#{@target}" if %i[private protected].include? @reader
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-initializer-3.0.4 lib/dry/initializer/builders/reader.rb
dry-initializer-3.0.3 lib/dry/initializer/builders/reader.rb