tailieunhanh - Best of Ruby Quiz Pragmatic programmers phần 5

bằng cách đi qua các đối tượng để chặn một trong khởi tạo (). Bên trong khối, người sử dụng có thể sử dụng truy cập thông để thiết lập chi tiết cho câu trả lời là sau khi. Phương pháp duy nhất thực sự có giá trị thảo luận ở đây là chuyển đổi (). | Answer 7. HighLine 110 elsif type Symbol elsif type Regexp string elsif Array OptionParser Completion string .last elsif Date DateTime .include type string elsif Proc type string end end def accept answer_object or answer_object end def valid string or string validate end end end This is really just a data class. It sets a bunch of defaults and then allows the user to change them to fit their needs by passing the object to a block in initialize . Inside the block the user can use the accessors to set details for the answer they are after. The only method really worth discussing here is convert . You can see that it supports many types the answer can be converted into including Integer Symbol or even DateTime. This method can do two interesting forms of conversion. First if the @type answer_type from the HighLine layer is set to an Array of values the method will autocomplete the user s answer to a matching value using code borrowed from OptionParser. Finally if you set @type to a Proc object it will be called to handle whatever custom conversion you need. Glance back at if you want to see an example. so far we ve seen the class system which could be used directly via require highline when needed. Most of the time though we would probably prefer global access to these methods. For that HighLine provides another file you could load with require highline import Report erratum Answer 7. HighLine 111 highline highline usr local bin ruby -w require highline require forwardable terminal module Kernel extend Forwardable def_delegators terminal agree ask say end The idea here is that we can stick a HighLine object in a global variable and then just modify Kernel to delegate bare agree ask or say calls to that object. The standard library Forwardable handles the latter part of that process for us via def_delegators . .

TỪ KHÓA LIÊN QUAN