Last active
December 27, 2015 05:49
-
-
Save Zhengquan/7276675 to your computer and use it in GitHub Desktop.
There’s no reason that yield and instance_eval DSLs need to be mutually exclusive. Far from it! In Ruby we encourage options, and it’s actually quite easy to provide a way to yield OR instance_eval based on the block passed in:
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
class Page | |
attr_accessor :name | |
def initialize(&block) | |
if block_given? | |
if block.arity == 1 | |
yield self | |
else | |
instance_eval(&block) | |
end | |
end | |
end | |
end | |
Page.new do | |
name = "this is a page" | |
end | |
Page.new do |page| | |
page.name = "this is a page" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment