オープンクラス
prepend
インクルードしたクラスの下に挿入される
Refinements、using
# 第3章
def refresh(options={})
defaults = {}
attributes = [:input, :output, :commands, :print, :quiet,
:exception_handler, :hooks]
attributes.each do |attribute|
defaults[attribute] = Pry.send attribute
end
# ...
defaults.merge!(options).each do |key, value|
send("#{key}=", value) if respond_to?("#{key}=")
end
true
end
class MyClass
define_method :my_method do |my_arg|
my_arg * 3
end
end
obj = MyClass.new
obj.my_method(2) # => 6
class Computer
def initialize(computer_id, data_source)
@id = computer_id
@data_source = data_source
end
def self.define_component(name)
define_method(name) do
info = @data_source.send "get_#{name}_info", @id
# price = ~~
# result = ~~
# return ~~
# result
end
end
define_component :mouse
define_component :cpu
define_component :keyboard
end
class Lawyer
def method_missing(method, *args)
puts "呼び出した : #{method}(#{args.join(', ')}"
puts "ブロックも渡した" if block_given?
end
end
class Computer
def initialize(computer_id, data_source)
@id = computer_id
@data_source = data_source
end
def method_missing(name)
super if !@data_source.respond_to?("get_#{name}_info")
info = @data_source.send("get_#{name}_info", @id)
# 省略
end
def respond_to_missing?(method, include_private = false)
@data_source.respond_to?("get_#{method}_info") || super
end
end