tags:

views:

46

answers:

2

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
A: 

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
Swanand
A: 

attr_reader is an example of what "Metaprogramming Ruby" calls a "Class Macro". If you wanted to, you could define your own class macro, such that you could do

Class SampleClass
  my_boolean_reader :server_error

  def initialize
    @server_error = false
  end
end

sample_object = SampleClass.new
sample_object.server_error? # => false
Andrew Grimm
Hello, and thank you for your response. What exactly is my_boolean_reader here? I got NoMethodError, so obviously I am missing something.
c64ification
@c64ification: I said you could define a method called `my_boolean_reader` that'd do what you were after.
Andrew Grimm
ok, that is interesting, thank you
c64ification