Created
November 26, 2012 04:18
-
-
Save rauchy/4146596 to your computer and use it in GitHub Desktop.
Blocks In-depth: instance_eval
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 MyLibrary | |
class Configuration | |
attr_accessor :protocol, :hostname, :port | |
end | |
attr_accessor :configuration | |
def configure(&block) | |
self.configuration ||= Configuration.new | |
self.configuration.instance_eval(&block) | |
end | |
end | |
m = MyLibrary.new | |
m.configure do |config| | |
config.protocol = "https" | |
config.hostname = "localhost" | |
config.port = 80 | |
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
class MyLibrary | |
class Configuration | |
def protocol(protocol) | |
@protocol = protocol | |
end | |
def hostname(hostname) | |
@hostname = hostname | |
end | |
def port(port) | |
@port = port | |
end | |
end | |
attr_accessor :configuration | |
def configure(&block) | |
self.configuration ||= Configuration.new | |
self.configuration.instance_eval(&block) | |
end | |
end | |
m = MyLibrary.new | |
m.configure do |config| | |
protocol "https" | |
hostname "localhost" | |
port 80 | |
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
p = proc { puts to_a } | |
[1,2,3,4,5].instance_eval(&p) # => [1,2,3,4,5] | |
OpenStruct.new(to_a: "HAI").instance_eval(&p) # => HAI |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment