lib/attributes_dsl/attribute.rb in attributes_dsl-0.0.2 vs lib/attributes_dsl/attribute.rb in attributes_dsl-0.1.0

- old
+ new

@@ -7,63 +7,78 @@ # @api private # # @author Andrew Kozin <Andrew.Kozin@gmail.com> # class Attribute - include Equalizer.new(:name) # @!attribute [r] name # # @return [Symbol] the name of the attribute # attr_reader :name - # @!attribute [r] default + # @!attribute [r] reader # - # @return [Object] the default value of the attribute + # @return [Boolean] whether an attribute should be readable # - attr_reader :default + attr_reader :reader - # @!attribute [r] required - # - # @return [Boolean] whether the attribute is required - # - attr_reader :required - - # @!attribute [r] coercer - # - # @return [Proc, nil] the coercer for the attribute - # - attr_reader :coercer - # Initializes the attribute # - # @param [Symbol] name + # @param [#to_sym] name # @param [Hash] options # @param [Proc] coercer # - # @option options [Object] :default - # @option options [Boolean] :required - # def initialize(name, options = {}, &coercer) - @name = name - @default = options.fetch(:default) {} - @required = default.nil? && options.fetch(:required) { false } - @coercer = coercer - - IceNine.deep_freeze(self) + @name = name.to_sym + @options = { coercer: coercer }.merge(options) + @reader = @options.fetch(:reader) { true } end - # Coerces an input assigned to the attribute + # A proc that transform a hash of attributes using current settings # - # @param [Object] input + # @return [Proc] # - # @return [Object] - # - def value(input) - coercer ? coercer[input] : input + def transformer + convert unless @options.empty? end - end # class Attribute + private -end # module AttributesDSL + def convert + @convert ||= Transprocs[:convert, name, presence, absence] + end + + def presence + [whitelist, blacklist, coercer].compact.reduce(:>>) || identity + end + + def absence + [missed, default].compact.reduce(:>>) || identity + end + + def identity + Transprocs[:identity] + end + + def missed + Transprocs[:missed, name] if @options[:required] + end + + def default + Transprocs[:default, name, @options[:default]] if @options[:default] + end + + def whitelist + Transprocs[:whitelist, name, @options[:only]] if @options[:only] + end + + def blacklist + Transprocs[:blacklist, name, @options[:except]] if @options[:except] + end + + def coercer + Transprocs[:coerce, name, @options[:coercer]] if @options[:coercer] + end + end +end