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
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With