Search code examples
rubyruby-style-guide

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?


Solution

  • 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) }