Skip to content

Commit

Permalink
Add array.coerce.
Browse files Browse the repository at this point in the history
  • Loading branch information
blambeau committed Jul 9, 2024
1 parent eb6125f commit 330f00a
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.6.3

* Add `coerce.array`

## 0.6.2 - 2022-09-29

* Add `key_hash` option to `core.mapping`.
Expand Down
43 changes: 43 additions & 0 deletions documentation/stdlib/coerce/array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# coerce.array

Coerces the input value to an array

```
coerce.array: Any -> Array
```

This lens convert its input to an Array.

Mimicing ruby, null is coerced to an empty array.
An array is kept unchanged.
Any other value is converted to a singleton array.

## Example

Applying the following lens:

```yaml
---
array.map:
on_error: 'null'
lenses:
- coerce.array
```
to the following input:
```yaml
---
- ~
- 'foo'
- ['foo', 'bar']
```
will return:
```yaml
---
- []
- ['foo']
- ['foo', 'bar']
```
6 changes: 6 additions & 0 deletions lib/monolens/stdlib/coerce.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,16 @@ def string(options, registry)
end
module_function :string

def array(options, registry)
Array.new(options, registry)
end
module_function :array

Monolens.define_namespace 'coerce', self
end
end
require_relative 'coerce/date'
require_relative 'coerce/date_time'
require_relative 'coerce/integer'
require_relative 'coerce/string'
require_relative 'coerce/array'
13 changes: 13 additions & 0 deletions lib/monolens/stdlib/coerce/array.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module Monolens
module Coerce
class Array
include Lens

signature(Type::Any, Type::Array)

def call(arg, world = {})
Array(arg)
end
end
end
end
13 changes: 13 additions & 0 deletions spec/monolens/stdlib/coerce/test_array.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
require 'spec_helper'

describe Monolens, 'coerce.array' do
subject do
Monolens.lens('coerce.array')
end

it 'works' do
expect(subject.call(12)).to eql([12])
expect(subject.call(nil)).to eql([])
expect(subject.call([12, 13])).to eql([12, 13])
end
end

0 comments on commit 330f00a

Please sign in to comment.