attr_reader with question mark in a name

Viewed 9118

Sorry for this, probably, really newbie question:

I want to define a getter that returns bool value. f.i.:

  attr_reader :server_error?

But then, how do I update it, as Ruby (1.9) throws syntax error if there is a question mark at the end:

#unexpected '='
@server_error? = true
self.server_error? = true
7 Answers

This question is old but with alias_method you can achieve that:

class Foo
  attr_reader :server_error
  alias_method :server_error?, :server_error

  # [...]
end

Basically the method server_error? will be an alias for the server_error method.

If you use Rails or ActiveSupport you can do it like:

private

def server_error?
   @server_error.present?
end

similar to Swanand, I would propose to add a method. In Ruby 3 you can use endless method definitions for a little more elegance:

def server_error? = !!@server_error
Related