Created
September 7, 2015 10:38
-
-
Save Yorgg/ea49085b9c1c17dedb70 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#Examples from 'meta programming in Ruby' | |
#These methods save you from manually typing out each method for the wrapper class. | |
#If the data source is updated (new methods) you also don't need to update this wrapper class. | |
#Dynamic Dispatch | |
class Computer | |
def initialize(computer_id, data_source) | |
@id = computer_id | |
@data_source = data_source | |
data_source.methods.grep(/^get_(.*)_info$/) { Computer.define_component $1 } | |
end | |
def self.define_component(name) define_method(name) { | |
info = @data_source.send "get_#{name}_info", | |
@id price = @data_source.send "get_#{name}_price", | |
@id result = "#{name.capitalize}: #{info} ($#{price})" | |
return "* #{result}" if price >= 100 | |
result } | |
end | |
end | |
#Using Method Missing: | |
class Computer | |
def initialize(computer_id, data_source) | |
@id = computer_id | |
@data_source = data_source | |
end | |
def method_missing(name, *args) | |
super if !@data_source.respond_to?("get_#{name}_info") | |
info = @data_source.send("get_#{name}_info", args[0]) | |
price = @data_source.send("get_#{name}_price", args[0]) | |
result = "#{name.to_s.capitalize}: #{info} ($#{price})" | |
return "* #{result}" if price >= 100 | |
result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment