Skip to content

Commit

Permalink
Merge pull request #471 from CharlieWWW94/enum_each_value_method
Browse files Browse the repository at this point in the history
Add Dry::Types::Enum#each_value method, with tests
  • Loading branch information
flash-gordon authored Jan 3, 2025
2 parents b346537 + efa1920 commit d250f60
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
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

0 comments on commit d250f60

Please sign in to comment.