metaprogramming-1-Dynamic Method

 

# cool dynamic method usage
class MyClass
	define_method :my_method do |my_arg|
		my_arg * 8
	end
end

m = MyClass.new
p m.my_method 8
p m.send(:my_method, 9)# a more complicated example
puts "============== Example ==============="
# Dynamic Example
# Dynamic Model
class MOUSE
	attr_accessor :price, :info, :c_id
	def initialize price, info, c_id
		@price, @info, @c_id = price, info, c_id
	end
end
class CPU
	attr_accessor :price, :info, :c_id
	def initialize price, info, c_id
		@price, @info, @c_id = price, info, c_id
	end
end
class KEYBOARD
	attr_reader :price, :info, :c_id
	def initialize price, info, c_id
		@price, @info, @c_id = price, info, c_id
	end
end
# Dynamic Method DS
class DS
	def initialize
		@data = []
	end
	
	def addCom *component
		component.each{|c| @data << c }
	end
	
	def count 
		@data.count
	end
	
	class << DS
		def define_get_method *component_name
			component_name.each do |each|			
				%w-_info _price-.each do |content|
					define_method ("get_" + each.to_s + content).to_sym do |c_id|
						comArray = @data.select{|x| x.c_id == c_id}
						com = comArray.select{|x| x.is_a? eval(each.to_s.upcase)}
						com[0].send(content[1..-1])
					end
				end
			end
		end
	end
	define_get_method :mouse, :keyboard, :cpu
end
#data prepare
k1 = KEYBOARD.new 10, "keyboard_1", 1
k2 = KEYBOARD.new 40, "keyboard_1", 2
k3 = KEYBOARD.new 100, "keyboard_1", 3
c1 = CPU.new 200, "cpu_1", 1
m1 = MOUSE.new 1000, "apple Inc", 1

ds = DS.new
ds.addCom k1, k2, k3, c1, m1
p ds.count
p (ds.get_mouse_info 1), (ds.get_mouse_price 1)
p ds.get_keyboard_info 1
p ds.get_cpu_info 1
# more about dynamic method
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 > 500
			result
		}
	end
end
puts "-----------------final invoke..-----------------"
c = Computer.new 1, ds
p c.keyboard
p c.mouse

你可能感兴趣的:(code,Ruby,usage)