Skip to content

Instantly share code, notes, and snippets.

@veezus
Created June 27, 2012 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veezus/3006462 to your computer and use it in GitHub Desktop.
Save veezus/3006462 to your computer and use it in GitHub Desktop.
# application.rb
class ApplicationDSL
attr_accessor :applications
def initialize
self.applications = []
end
def application(name, &block)
application = Application.new(name)
applications << application
application.instance_eval &block
application
end
def self.execute(dsl)
new.tap do |context|
context.instance_eval(dsl)
end
end
end
class Application
attr_accessor :name, :roles
def initialize(name)
self.name = name
self.roles = []
end
def roles(*roles)
if roles.empty?
@roles
else
@roles = [] if @roles.nil?
if roles[0].kind_of? Array
@roles += roles[0]
else
@roles = []
@roles << roles[0]
end
self
end
end
end
# provided_sample.rb
application "foo" do
roles %w{a b c d}
end
# desired_sample.rb
application "foobear" do
roles %w(polar grizzly black)
end
application "pokercat" do
roles %w(lion tiger panther)
end
# parse.rb
#! /usr/bin/env ruby
require 'application.rb'
provided_sample = File.read(File.expand_path(File.join('.', 'provided_sample.rb')))
applications = ApplicationDSL.execute(provided_sample).applications
puts "Provided sample roles:"
puts "===================="
applications.each do |app|
puts "Roles for #{app.name}"
puts app.roles.join(', ')
end
puts
desired_sample = File.read(File.expand_path(File.join('.', 'desired_sample.rb')))
applications = ApplicationDSL.execute(desired_sample).applications
puts "Desired sample roles:"
puts "====================="
applications.each do |app|
puts "Roles for #{app.name}"
puts app.roles.join(', ')
end
# output
Provided sample roles:
====================
Roles for foo
a, b, c, d
Desired sample roles:
=====================
Roles for foobear
polar, grizzly, black
Roles for pokercat
lion, tiger, panther
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment