Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attr_reader with question mark in a name

Tags:

ruby

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
like image 443
Ernest Avatar asked Oct 25 '10 10:10

Ernest


3 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.

like image 183
Pigueiras Avatar answered Nov 09 '22 05:11

Pigueiras


I suggest defining your own method rather than using :attr_reader

def server_error?
  !!@server_error # Or any other idiom that you generally use for checking boolean
end

for brevity's sake, you could do it in one line:

def server_error?; !!@server_error; end
like image 25
Swanand Avatar answered Nov 09 '22 05:11

Swanand


If you need to define such methods repeatedly, define a module named AttrBoolean:

module AttrBoolean
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def attr_boolean(*names)
      names.each do |name|
        define_method(:"#{name}=") do |value|
          instance_variable_set(:"@#{name}", value)
        end

        define_method(:"#{name}?") do
          !!instance_variable_get(:"@#{name}")
        end
      end
    end
  end
end

You can use this in the following manner:

class Foo
  include AttrBoolean

  attr_boolean :server_error, :resolved
end

f = Foo.new
f.server_error = true
f.resolved = false
f.server_error? # => true
f.resolved?     # => false

Note that getter methods without question mark are not defined. The expression f.server_error throws an exception.

like image 10
Tsutomu Avatar answered Nov 09 '22 07:11

Tsutomu