Sha256: cece31d30b43cc5dfad6a93331e30640e06863197fe8dd2b9a231fa9f7f05051

Contents?: true

Size: 1.04 KB

Versions: 4

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

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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dry-initializer-3.0.2 lib/dry/initializer/builders/reader.rb
dry-initializer-3.0.1 lib/dry/initializer/builders/reader.rb
dry-initializer-3.0.0 lib/dry/initializer/builders/reader.rb
dry-initializer-2.5.0 lib/dry/initializer/builders/reader.rb