Created
November 4, 2020 18:59
-
-
Save serradura/2086b0bcafaf60c6ca1d476357b575e4 to your computer and use it in GitHub Desktop.
u-attributes: using accept to validate the attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'u-attributes', '~> 2.6.0' | |
end | |
class SumNumbers | |
include Micro::Attributes.with(:initialize, accept: :strict) | |
attribute :numbers, accept: -> arg do | |
arg.is_a?(Array) && arg.all? { |value| value.is_a?(Numeric) } | |
end | |
def call | |
numbers.reduce(:+) | |
end | |
end | |
puts SumNumbers.new(numbers: [1, 2, 3]).call | |
# 6 | |
puts SumNumbers.new(numbers: [1, '2', 3]).call | |
# One or more attributes were rejected. Errors: (ArgumentError) | |
# * "numbers" is invalid |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'u-attributes', '~> 2.6.0' | |
end | |
ArrayOf = -> kind do | |
-> arg { arg.is_a?(Array) && arg.all? { |value| value.is_a?(kind) } } | |
end | |
class SumNumbers | |
include Micro::Attributes.with(:initialize, accept: :strict) | |
attribute :numbers, accept: ArrayOf[Numeric] | |
def call | |
numbers.reduce(:+) | |
end | |
end | |
puts SumNumbers.new(numbers: [1, 2, 3]).call | |
# 6 | |
puts SumNumbers.new(numbers: [1, '2', 3]).call | |
# One or more attributes were rejected. Errors: (ArgumentError) | |
# * "numbers" is invalid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment