I'm trying to do a DSL, in which the user can pass a block and expect an instance variable @arg to be defined. This is a full example with a unit test failing:

# Implementation
class Filter
  def initialize
    @arg = 'foo'
  end

  def self.filters &block
    define_method :filter do |els|
      els.select &block
    end
  end
end

# Usage
class Foo < Filter
  filters {|el| el == @arg}
end

# Expected behavior
describe 'filters created with the DSL' do
  subject { Foo.new }
  it 'can use @arg in the filters block' do
    els = %w[notthearg  either  foo  other]
    expect(subject.filter els).to be_eql(['foo'])
  end
end

Using pry or putting puts statements inside the block, I can see that @arg is nil. But Foo.new.instance_variable_get :@arg correctly outputs foo, so it must be related to some scoping rules.

What do I need to change in the implementation to make the test pass and the DSL to work?

1 Answers

2
Amadan On Best Solutions

instance_exec to rescue!

class Filter
  def initialize
    @arg = 'foo'
  end

  def self.filters &block
    define_method :filter do |els|
      els.select { |e| self.instance_exec(e, &block) }
    end
  end
end

class Foo < Filter
  filters {|el| el == @arg }
end

Foo.new.filter(%w[notthearg  either  foo  other])
# => ["foo"]

Caution: Make sure this is very well documented, since any shenanigans involving instance_exec or its cousins are breaking programmer expectations left and right - by design, you're destroying the concept of "scope". I'm pretty sure OP knows this, but it is worth putting down on the proverbial paper.

Also, consider using accessors rather than plain instance variables - accessors are checked, and variables are not. i.e. { |el| el == urg } will result in an error, but { |el| el == @urg } will silently fail (and filter for nil).