https://github.com/simonneutert/ruby_dsl_example
Simple DSL Example in Ruby
https://github.com/simonneutert/ruby_dsl_example
dsl example metaprogramming ruby
Last synced: 4 months ago
JSON representation
Simple DSL Example in Ruby
- Host: GitHub
- URL: https://github.com/simonneutert/ruby_dsl_example
- Owner: simonneutert
- Created: 2017-04-12T16:00:17.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2022-06-16T19:59:34.000Z (over 3 years ago)
- Last Synced: 2025-04-06T10:02:35.499Z (10 months ago)
- Topics: dsl, example, metaprogramming, ruby
- Language: Ruby
- Size: 3.91 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: Readme.md
Awesome Lists containing this project
README
check out [instance_eval](https://apidock.com/ruby/Object/instance_eval), because this is where the magic happens
``` ruby
# to not pollute the global namespace, wrap your DSL in a class
module DslWrapper
class Post
def initialize(user)
@user = user
@post = []
@extras = {}
end
def text(str)
@post << str
self
end
def hashtag(*strs)
strs.each do |str|
@post << '#' + str
end
self
end
def link(str)
@post << str
self
end
def post_on_facebook
fb_text = @post.join(' ')
begin
if fb_text.length <= 440
puts "#{@user}: #{fb_text}"
puts @extras.inspect unless @extras.empty?
else
raise 'Your post is too long.'
end
rescue
puts "I can't tweet this, your tweet is too long, sorry."
end
end
def method_missing(method, *args)
@extras[method] = args.join(', ')
end
end
end
# your exposed DSL method
def post_as(user, text = nil, &block)
post = DslWrapper::Post.new(user)
post.text(text) if text
post.instance_eval(&block) if block_given?
post.post_on_facebook
end
# granular
post_as 'markz' do
text """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
hashtag 'ruby'
hashtag 'dsl'
link 'http://www.simon-neutert.de'
sexy 'objects'
end
# multiple hashtags
post_as 'markz' do
text 'my dsl works'
hashtag 'ruby', 'dsl'
link 'http://www.simon-neutert.de'
sexy 'classy'
end
# chaining
post_as 'markz' do
text("Mic check...").hashtag("one", "two").link('http://www.simon-neutert.de')
sexy 'bit'
end
# one liner
post_as 'markz', 'Hi, I am Mark_Z!'
```