Val
Val

Reputation: 1350

Ruby 2.1: Forwardable Module and def_delegators

I have a question about a refactoring I have done on an example.

Here is the original code:

class Parts
  attr_reader :parts

  def initialize(parts)
    @parts = parts
  end

  def size
    parts.size
  end

  def spares
    parts.select{|part| part.needs_spare}
  end
end

Here is the refactored code:

require 'forwardable'
class Parts
  extend Forwardable
  def_delegators :@parts, :size, :each
  include Enumerable

  def initialize(parts)
    @parts = parts
  end

  def spares
    select{|part| part.needs_spare}
  end
end

In the spares method the original code executed "parts.select{|part| part.needs_spare}" and then in the refactoring it was adjusted to "select{|part| part.needs_spare}". How does the new spares method know what instance variable it is selecting from?

Upvotes: 1

Views: 601

Answers (1)

Amadan
Amadan

Reputation: 198314

  • In the new code, select is self.select.
  • self.select, as all methods in Enumerable, uses self.each.
  • self.each is forwarded to @parts.each

Upvotes: 5

Related Questions