Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Dry::Types::Enum#each_value method, with tests #471

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/dry/types/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ def to_ast(meta: true)
def to_s
PRINTER.(self)
end

# Iterate over each enum value
#
# @return [Array, Enumerator]
#
# @api public
def each_value(&block)
values.each(&block)
end

alias_method :inspect, :to_s

private
Expand Down
32 changes: 32 additions & 0 deletions spec/dry/types/enum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,38 @@
end
end

describe "#each_value" do
context "simple enumeration" do
subject(:type) { Dry::Types["nominal.integer"].enum(4, 5, 6) }

it "iterates over keys" do
expect(type.each_value.to_a).to eql([4, 5, 6])
end

it "returns enumerator" do
enumerator = type.each_value

expect(enumerator.next).to be(type.values.first)
end
end

context "mapping" do
let(:mapping) { {0 => "draft", 10 => "published", 20 => "archived"} }

subject(:type) { Dry::Types["nominal.integer"].enum(mapping) }

it "returns the enum values" do
expect(type.each_value.to_a).to eq([0, 10, 20])
end

it "returns enumerator" do
enumerator = type.each_value

expect(enumerator.next).to be(type.values.first)
end
end
end

describe "#constructor" do
subject(:type) { Dry::Types["nominal.integer"].enum(4, 5) }

Expand Down