lib/dry/initializer/attribute.rb in dry-initializer-1.0.0 vs lib/dry/initializer/attribute.rb in dry-initializer-1.1.0
- old
+ new
@@ -1,10 +1,60 @@
module Dry::Initializer
# Contains definitions for a single attribute, and builds its parts of mixin
class Attribute
+ class << self
+ # Collection of additional dispatchers for method options
+ #
+ # @example Enhance the gem by adding :coercer alias for type
+ # Dry::Initializer::Attribute.dispatchers << -> (string: nil, **op) do
+ # op[:type] = proc(&:to_s) if string
+ # op
+ # end
+ #
+ # class User
+ # extend Dry::Initializer
+ # param :name, string: true # same as `type: proc(&:to_s)`
+ # end
+ #
+ def dispatchers
+ @@dispatchers ||= []
+ end
+
+ def new(source, coercer = nil, **options)
+ options[:source] = source
+ options[:target] = options.delete(:as) || source
+ options[:type] ||= coercer
+ params = dispatchers.inject(options) { |h, m| m.call(h) }
+
+ super(params)
+ end
+
+ def param(*args)
+ Param.new(*args)
+ end
+
+ def option(*args)
+ Option.new(*args)
+ end
+ 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)
+ validate
+ end
+
+ def ==(other)
+ source == other.source
+ end
+
# definition for the getter method
def getter
return unless reader
command = %w(private protected).include?(reader.to_s) ? reader : :public
@@ -15,19 +65,9 @@
|#{command} :#{target}
RUBY
end
private
-
- def initialize(source, coercer = nil, **options)
- @source = source
- @target = options.fetch(:as, source)
- @coercer = coercer || options[:type]
- @reader = options.fetch(:reader, :public)
- @default = options[:default]
- @optional = !!(options[:optional] || @default)
- validate
- end
def validate
validate_target
validate_default
validate_coercer