Skip to content

Instantly share code, notes, and snippets.

@rauchy
Created November 26, 2012 04:18
Show Gist options
  • Save rauchy/4146596 to your computer and use it in GitHub Desktop.
Save rauchy/4146596 to your computer and use it in GitHub Desktop.
Blocks In-depth: instance_eval
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
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
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