TIL: Object#presence_in
Rails adds the presence_in
method to the Object
class. It basically returns
the receiver if itβs included in the given object, or nil
otherwise.
class Object
def presence_in(another_object)
in?(another_object) ? self : nil
end
end
To understand how it works, it might be useful to look at the definition of
Object#in?
, which is basically #include?
with left and right-hand side
swapped.
def in?(another_object)
another_object.include?(self)
rescue NoMethodError
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
end
I think this is particularly useful for allowlists like
class UsersController < BaseController
def index
sort_by = params[:sort_by].presence_in(["created_at", "id", "name"])
@users = User.sort_by(sort_by)
end
end
Note that itβs really easy to add a default/fallback value in case you get a bad value.