RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

Using private attr_accessors is wrong

I’m working on an existing Rails application and there’s one pattern I see repeating often that I’m puzzled with. It’s especially common in service objects. Here’s couple of reasons you should not use private attr_accessors.

Comments

While I agree it’s in general bad to use a private attr_accessor (because of the issues you’ve outline in your blog post), I really dig the usage of a private attr_reader. IMHO it makes the code easier to read (because it’s not cluttered with @’s) and easier to change - say you no longer set your @thing to one of the arguments during initialization, but you need something more complex. Super easy to change with an attr_reader, because you can simply replace it with a method.

I suggest Sandi Metz’s “Practical Object-Oriented Design In Ruby” book (“Hide Instance Variables” in Chapter 2).

I use “protected” attr_accessors Very useful for catching careless typo

Instance variables are not very cool to use because a simple typo in it’s name results into Ruby silently returning nil instead of raising an exception. That’s why in our codebase ivars are only allowed in initializers.

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in