lib/dry/initializer/attribute.rb in dry-initializer-1.2.0 vs lib/dry/initializer/attribute.rb in dry-initializer-1.3.0

- old
+ new

@@ -38,16 +38,17 @@ end attr_reader :source, :target, :coercer, :default, :optional, :reader def initialize(options) - @source = options[:source] - @target = options[:target] - @coercer = options[:type] - @default = options[:default] - @optional = !!(options[:optional] || @default) - @reader = options.fetch(:reader, :public) + @source = options[:source] + @target = options[:target] + @coercer = options[:type] + @default = options[:default] + @optional = !!(options[:optional] || @default) + @reader = options.fetch(:reader, :public) + @undefined = options.fetch(:undefined, true) validate end def ==(other) source == other.source @@ -56,16 +57,16 @@ # definition for the getter method def getter return unless reader command = %w(private protected).include?(reader.to_s) ? reader : :public - <<-RUBY.gsub(/^ *\|/, "") - |undef_method :#{target} if method_defined?(:#{target}) || protected_method_defined?(:#{target}) || private_method_defined?(:#{target}) - |def #{target} - | @#{target} unless @#{target} == Dry::Initializer::UNDEFINED - |end - |#{command} :#{target} + <<-RUBY + undef_method :#{target} if method_defined?(:#{target}) || + protected_method_defined?(:#{target}) || + private_method_defined?(:#{target}) + #{reader_definition} + #{command} :#{target} RUBY end private @@ -73,10 +74,22 @@ validate_target validate_default validate_coercer end + def undefined + @undefined ? "Dry::Initializer::UNDEFINED" : "nil" + end + + def reader_definition + if @undefined + "def #{target}; @#{target} unless @#{target} == #{undefined}; end" + else + "attr_reader :#{target}" + end + end + def validate_target return if target =~ /\A\w+\Z/ fail ArgumentError.new("Invalid name '#{target}' for the target variable") end @@ -94,10 +107,13 @@ default ? { :"#{type}_#{source}" => default } : {} end def coercer_hash(type) return {} unless coercer - value = proc { |v| v == Dry::Initializer::UNDEFINED ? v : coercer.(v) } + + value = coercer unless @undefined + value ||= proc { |v| v == Dry::Initializer::UNDEFINED ? v : coercer.(v) } + { :"#{type}_#{source}" => value } end end end