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

Composable#static #20

Merged
merged 2 commits into from
Sep 6, 2024
Merged

Composable#static #20

merged 2 commits into from
Sep 6, 2024

Conversation

ismasan
Copy link
Owner

@ismasan ismasan commented Sep 6, 2024

#static

A type that always returns a valid, static value, regardless of input.

ten = Types::Integer.static(10)
ten.parse(10) # => 10
ten.parse(100) # => 10
ten.parse('hello') # => 10
ten.parse() # => 10
ten.metadata[:type] # => Integer

Useful for data structures where some fields shouldn't change. Example:

CreateUserEvent = Types::Hash[
  type: Types::String.static('CreateUser'),
  name: String,
  age: Integer
]

Note that the value must be of the same type as the starting step's target type.

Types::Integer.static('nope') # raises ArgumentError

This usage is the same as using Types::Static['hello']directly.

Block usage

Passing a proc will evaluate the proc on every invocation. Use this for generated values.

random_number = Types::Numeric.static { rand }
random_number.parse # 0.32332
random_number.parse('foo') # 0.54322 etc

Note that in this mode, the type of generated value must match the initial step's type, validated at invocation.

random_number = Types::String.static { rand } # this won't raise an error here
random_number.parse # raises Plumb::ParseError because `rand` is not a String

@ismasan ismasan merged commit a70a237 into main Sep 6, 2024
1 check passed
@ismasan ismasan deleted the static_helper branch September 6, 2024 14:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant