dom
dom

Reputation: 444

Are ruby methods ending on '?' allowed to change stuff?

I was going through some code in one of our RoR apps in our company. And I noticed, that sometimes, there is used method with question mark, such like following method used in one of our controllers.

  # readonly checker
  # @param url to redirect or nil
  # if url set up, goes to url with note "not allowed because readonly"
  # else @returns true / false
  def readonly?(url = nil)
    if current_user_can_access?(:readonly)

      message = I18n.t(:auth_readonly)
      if request.xhr?
        response.status = 403
        render json: { error: message }
      else
        redirect_to url, notice: message unless url.nil?
      end
      true
    else
      false
    end
  end

My question is, whether it is acceptable (and usual), that readonly? also redirects somewhere.

I am used to implementing question mark methods, that only return values convertable to boolean and do not make changes in models, DB...

Upvotes: 0

Views: 90

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369468

A predicate method with side-effects violates the Principle of Least Astonishment IMO. It may have "internal" side-effects, e.g. memoize some internal value, but it should be "externally" pure / referentially transparent.

If you subscribe to Bertrand Meyer's Command-Query Separation Principle, then predicate methods are Queries (which should not have side-effects). redirect_to is a Command (which has only side-effects and no return value). The two should not mix.

Upvotes: 8

mellowfish
mellowfish

Reputation: 674

? methods (aka "predicate" methods) are an example of a "query" method, which should only return a value, with no side effects.

before_action style methods are what are called "command" methods, which have side-effects and don't return a meaningful result beyond an occasional status/error flag.

So the answer here is no, don't redirect from a ? method.

Upvotes: 0

Related Questions