anger
anger

Reputation: 1018

Usage of `Object#send` method as a best practice

It is hard to identify the usages of code like below:

[:create, :update, :pause].each { |action| send("to_#{action}") }

Are there any other reasons that this is an anti-pattern?

Upvotes: 1

Views: 520

Answers (2)

tadman
tadman

Reputation: 211560

There's reasons to use this, and there's reasons to avoid it. This trivial example is a case of an anti-pattern because it's a fixed array and it would be more concise to write:

create
update
pause

Where you have a case for using it is when the array isn't necessarily static, where there might be modifications, especially when used in the context of a DSL.

Rails employs this for the before_validation handler chain, for example, where it has a list of Symbol references or Proc functions to call:

before_validation :check_sanity
before_validation lambda { do_something(1) }

Upvotes: 1

Bart
Bart

Reputation: 2656

It's not an anti-pattern. It's a part of the language. You should avoid it for the reasons mentioned but sometimes it's the only option. I don't think there are any significant drawbacks performance wise. As for keeping things OOP you should suggest switching to public_send - it's the recommended way.

Upvotes: 5

Related Questions