Created
September 17, 2013 17:11
-
-
Save tobiashm/6597402 to your computer and use it in GitHub Desktop.
A Ruby DSL builder helper. By using a delegator object we can isolate the DSL methods, making them only available inside the `build` block.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "delegate" | |
module DSL | |
def self.build(klass, &block) | |
delegator_klass = Class.new(SimpleDelegator, &block) | |
klass.define_singleton_method(:build) do |*args, &block| | |
klass.new(*args).tap { |base| delegator_klass.new(base).instance_eval(&block) } | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "minitest/spec" | |
require "minitest/autorun" | |
require_relative "dsl" | |
describe DSL do | |
class TestConfig | |
attr_reader :file_paths | |
def initialize | |
@file_paths = [] | |
end | |
def add_paths(*paths) | |
@file_paths += paths.map { |p| File.expand_path(p) } | |
end | |
DSL.build(self) do | |
def files(*paths) | |
add_paths(*paths) | |
end | |
end | |
end | |
it "can add a build method with scoped DSL methods" do | |
config = TestConfig.build do | |
files "dsl.rb", "dsl_spec.rb" | |
end | |
config.file_paths.must_equal %w[dsl.rb dsl_spec.rb].map { |f| File.expand_path(f) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment