~ RICH CODES

TIL: Object#presence_in

January 06, 2022 | 1 minute read | ✍🏼 Fix typo

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.

class UsersController < BaseController
  def index
    sort_by = params[:sort_by].presence_in(["created_at", "id", "name"]) || "id"
    @users = User.sort_by(sort_by)
  end
end

Categories

TIL rails