Vibescript Showcase
Hash projection
Remove, select, merge, and fetch fields from a hash.
Source
showcase/collections/hash_projection.vibe
# title: Hash projection
# category: Vibescript Showcase
# difficulty: Showcase
# summary: Remove, select, merge, and fetch fields from a hash.
# description: except removes private fields, slice selects public fields, and fetch_values fails when a required field is missing.
# tags: collections, hashes, projection
# vibe: 0.4
def public_view(record: hash) -> hash
record.except(:password_hash, :ssn)
end
def summary(record: hash) -> hash
record.slice(:id, :name, :plan)
end
def with_defaults(record: hash) -> hash
{ plan: "free", region: "us" }.merge(record)
end
def required_fields(record: hash) -> array
record.fetch_values(:id, :email)
end
def run
record = {
id: 42,
name: "Ada",
email: "ada@vibe.dev",
plan: "pro",
password_hash: "x1y2z3",
ssn: "000-00-0000"
}
{
public_view: public_view(record),
summary: summary(record),
with_defaults: with_defaults({ id: 7, name: "Lin" }),
required_fields: required_fields(record),
contacts: record.values_at(:name, :email)
}
end
Output
Press Run example to run this code.