Clamp strings, symbols, array or hashes
The clamped gem allows to filter values by a provided whitelist. For example,
"apple".clamped(%w[apple banana]) # "apple". If
apple is not part of the array,
nil is returned. This is e.g. useful to filter values provided by user input.
Ruby already supports clamping numbers:
10.clamp(12, 20) # 12
The clamped gem extends this to strings, symbols, arrays and hashes.
"apple".clamped(%w[banana orange]) # nil
"apple".clamped(%w[apple banana]) # "apple"
This is mostly useful when whitelisting user input:
ROLES = ["admin", "user"]
# assume params[:role] == "superadmin"
params[:role].clamped(ROLES, default: "guest") # "guest"
gem install clamped or put
gem "clamped" in your
Gemfile. More information on https://github.com/metikular/clamped