Created
March 13, 2009 06:28
-
-
Save fairchild/78455 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
| class Box | |
| def options(h={}) | |
| @options ||= self.class.options.merge(h) | |
| end | |
| def self.options(h={}) | |
| @class_options ||= h | |
| end | |
| def self.define_defaults(ops={}) | |
| puts "# defining #{self} defaults: #{ops.inspect} - " | |
| ops.each do |k, v| | |
| self.options[k.to_sym] = v | |
| methods_to_define = { | |
| # :class_attr => "class << self; @#{k}=#{v}; def #{k}; @#{k}; end; end", | |
| :class_get => "class << self; def #{k}; self.options[:#{k}]; end; end", | |
| :instance_get_and_set => "def #{k}(i=nil); i ? options[:#{k}] = i : options[:#{k}]; end", | |
| :instance_set_with_eql => "def #{k}=(v);options[:#{k}]=v;end" | |
| } | |
| methods_to_define.each {|method, definition| | |
| puts definition | |
| class_eval definition | |
| } | |
| end | |
| end | |
| end | |
| defaults = {:open => false, :color=>'brown', :optioddns=>'optional'} | |
| Box.define_defaults(defaults) | |
| p Box.options | |
| p Box.open # == false | |
| p Box.color #=='brown' | |
| puts "-- should be all true --" | |
| p Box.open == false | |
| p Box.color =='brown' | |
| b=Box.new | |
| p b.open == false | |
| p b.color == 'brown' | |
| b.color= 'red' | |
| p b.color == 'red' | |
| puts '-- done --' | |
| p b.inspect | |
| p Box.options | |
| p Box.public_methods(false) | |
| p b.public_methods(false) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment