Sha256: 4e27a8e38d4d8f3e93f36e36c6649b3a40c85b04ff264efe867fb16f62622746

Contents?: true

Size: 1.04 KB

Versions: 5

Compression:

Stored size: 1.04 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 #{@ivar} == Dry::Initializer::UNDEFINED",
        "end"
      ]
    end

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

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
dry-initializer-2.4.0 lib/dry/initializer/builders/reader.rb
dry-initializer-2.3.0 lib/dry/initializer/builders/reader.rb
dry-initializer-2.2.0 lib/dry/initializer/builders/reader.rb
dry-initializer-2.1.0 lib/dry/initializer/builders/reader.rb
dry-initializer-2.0.0 lib/dry/initializer/builders/reader.rb