You are on page 1of 9

DSL PART 1

DOMAIN SPECIFIC LANGUAGES


a language that has terminology and
DSL
constructs designed for a specific domain

External DSL a standalone DSL

Internal DSL a DSL implemented within another


programming language

DSL PART 1
OUR SAMPLE DSL
tweet_as 'markkendall' do
mention 'codeschool'
valid Ruby syntax
text 'I made a DSL!' with custom terminology
hashtag 'hooray'
hashtag 'ruby'
link 'http://codeschool.com'
end

@codeschool I made a DSL! #hooray #ruby http://codeschool.com

DSL PART 1
FIRST IMPLEMENTATION
tweet_as 'markkendall' do def text(str)
mention 'codeschool' @tweet << str
text 'I made a DSL!' end
hashtag 'hooray'
hashtag 'ruby' def mention(user)
link 'http://codeschool.com' @tweet << "@" + user
end end

def hashtag(str)
def tweet_as(user) @tweet << "#" + str
@user = user end
@tweet = []
yield def link(str)
submit_to_twitter @tweet << str
end end

DSL PART 1
FIRST IMPLEMENTATION
tweet_as 'markkendall' do def tweet_as(user)
mention 'codeschool' @user = user
text 'I made a DSL!' @tweet = []
hashtag 'hooray' yield
hashtag 'ruby' submit_to_twitter
link 'http://codeschool.com' end
end
def submit_to_twitter
tweet_text = @tweet.join(' ')
puts "#{@user}: #{tweet_text}"
We polluted our end

namespace!! def text(str)


@tweet << str
end
...

DSL PART 1
NAMESPACE POLLUTION
def tweet_as(user) class Tweet
tweet = Tweet.new(user) def initialize(user)
yield tweet @user = user
tweet.submit_to_twitter @tweet = []
end end

def submit_to_twitter

new block parameter tweet_text = @tweet.join(' ')


puts "#{@user}: #{tweet_text}"
end

def text(str)

m en ta t i on @tweet << str


imp l e end

n t c h a n g e ...
did end

DSL PART 1
NAMESPACE POLLUTION
def tweet_as(user)
tweet = Tweet.new(user)
yield tweet
tweet.submit_to_twitter
end

tweet_as 'markkendall' do |tweet|


tweet.mention 'codeschool'
we ma d e our
tweet.text 'I made a DSL!'
tweet.hashtag 'hooray'
DSL sy n ta x ug l y
tweet.hashtag 'ruby'
tweet.link 'http://codeschool.com'
end

DSL PART 1
INSTANCE_EVAL
def tweet_as(user, &block )
tu re t h e b lo c k ,
tweet = Tweet.new(user) c a p
i n s ta n c e_ e va l
tweet.instance_eval(&block)
tweet.submit_to_twitter pass it to
end

tweet_as 'markkendall' do
mention 'codeschool'
our original, clean syntax
text 'I made a DSL!'
hashtag 'hooray'
is back!
hashtag 'ruby'
link 'http://codeschool.com'
end

DSL PART 1
METHOD CHAINING
tweet_as 'markkendall' do
mention 'codeschool'
text('I made a DSL!').hashtag('hooray').hashtag('ruby')
link 'http://codeschool.com'
end

i r es th es e pa r en s
Ruby req u
def text(str) def mention(user) def hashtag(str)
@tweet << str @tweet << "@" + user @tweet << "#" + str
self self self
end end end

return self
DSL PART 1

You might also like