Skip to content

Proposed stuff to add

Adam Alboyadjian edited this page Mar 2, 2023 · 2 revisions

Prefer attr_accessors over instance variables.

Rationale:

When you try and access an instance variable that doesn't exist because you've got a typo in the variable name, ruby happily returns nil. If you assign to an instance variable with a typo in it, ruby happily does the assignment.

If you try and assign to an accessor with a typo in it, you'll get a no-method error. If you try and read from an accessor with a typo in it, you'll get a no-method error.

While it may result in you exposing unnecessary setters/getters, there's no real security benefit to preventing that as you can always call something.send or set_instance_variable to get around the security. But using the accessor can save developer time and reduce future bugs.

Generally, the only time we use attr_reader or attr_writer instead of attr_accessor is if need to define a custom getter or setter that does something different.

Clone this wiki locally