I'm trying to add a property called "enabled?" to a model with both a getter and a setter. However, when I do the following:
def enabled?= value
# .. logic goes here ..
end
I get syntax error, unexpected '?', expecting '\n' or ';'
What should I be doing instead?
Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the program's convenience, getter starts with the word “get” followed by the variable name. While Setter sets or updates the value (mutators). It sets the value for any variable used in a class's programs.
It is not necessary to write getter or setter for all private variables. It is just a good practice. But without any public function you can not access the private data(variable) of the class.
In the Advanced Object lessons, in the Getter unit: “Another thing to keep in mind when using getter (and setter) methods is that properties cannot share the same name as the getter/setter function.”
The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.
In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.
Setters only take one parameter because they are special methods that expect a value and set the property to that value, upon validation of type.
Yes, ruby syntax only allows ?
in method names if it's the last character, so foo?=
is not valid. One thing you could do, that would be pretty idiomatic, is to define enabled?
, enable
and disable
(or enable!
and disable!
if you want to emphasize that they're mutating methods).
If that doesn't fit your needs, you can just name the methods enabled?
and enabled=
and just live with the slight incosistency between the names.
A method name in ruby starts with a lower case letter or underscore optionally followed by upper and lower case letters underscores and digts. A method name may optionally end with a question mark, exclamation mark or equals sign.
So you can't!
You could follow the usual ruby idiom of defining enabled as follow :-
def enabled?
@enabled
end
def enabled=(value)
@enabled = value
end
To summarise. If you want to expose properties to the outside world then ensure your variable name will allow that within the confines of the rules for method names.
One small variation would be to alias the getter method, allowing both enabled
and enabled?
:
def enabled
@enabled
end
def enabled=(value)
@enabled = value
end
alias_method :enabled?, :enabled
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