Module: Sandbox
- Defined in:
- lib/sandbox.rb
Constant Summary collapse
- @@created_classes =
keep track of the top-level classes we create, so we can destroy only those methods if we get mixed in somewhere
[]
Class Method Summary collapse
- .add_attributes(klass, *attrs) ⇒ Object
- .add_class(klass) ⇒ Object
- .add_class_method(klass, method_name, proc_obj = nil, &blk) ⇒ Object
- .add_method(klass, method_name, proc_obj = nil, &blk) ⇒ Object
- .cleanup! ⇒ Object
- .const_get_from_string(klass) ⇒ Object
- .const_set_from_string(delimited_klasses) ⇒ Object
- .created_classes ⇒ Object
- .scoop! ⇒ Object
Class Method Details
.add_attributes(klass, *attrs) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/sandbox.rb', line 11 def self.add_attributes(klass, *attrs) self.const_get_from_string(klass).class_eval do attr_accessor *attrs # set up the 'initialize' method to assign the attributes define_method(:initialize) do |*value_hash| value_hash = value_hash.first value_hash ||= {} value_hash.each do |k, v| instance_variable_set("@#{k.to_s}", v) end end end end |
.add_class(klass) ⇒ Object
7 8 9 |
# File 'lib/sandbox.rb', line 7 def self.add_class(klass) const_set_from_string(klass) end |
.add_class_method(klass, method_name, proc_obj = nil, &blk) ⇒ Object
30 31 32 33 34 |
# File 'lib/sandbox.rb', line 30 def self.add_class_method(klass, method_name, proc_obj=nil, &blk) singleton = ( class << self.const_get_from_string(klass); self end) singleton.send(:define_method, method_name, proc_obj || blk) end |
.add_method(klass, method_name, proc_obj = nil, &blk) ⇒ Object
26 27 28 |
# File 'lib/sandbox.rb', line 26 def self.add_method(klass, method_name, proc_obj=nil, &blk) self.const_get_from_string(klass).send(:define_method, method_name, proc_obj || blk) end |
.cleanup! ⇒ Object
36 37 38 |
# File 'lib/sandbox.rb', line 36 def self.cleanup! constants.each { |klass| remove_const klass } end |
.const_get_from_string(klass) ⇒ Object
48 49 50 |
# File 'lib/sandbox.rb', line 48 def self.const_get_from_string(klass) klass.split("::").inject(self) { |const, klass| const.const_get(klass) } end |
.const_set_from_string(delimited_klasses) ⇒ Object
52 53 54 55 56 57 58 59 60 |
# File 'lib/sandbox.rb', line 52 def self.const_set_from_string(delimited_klasses) # try to const_get before set const_set to avoid "already initialized" warnings delimited_klasses.split("::").inject(self) do |const, klass| const.constants.collect(&:to_s).include?(klass.to_s) ? const.const_get(klass) : const.const_set(klass, Class.new) end @@created_classes << delimited_klasses.split("::").first @@created_classes.uniq! end |
.created_classes ⇒ Object
44 45 46 |
# File 'lib/sandbox.rb', line 44 def self.created_classes @@created_classes end |
.scoop! ⇒ Object
40 41 42 |
# File 'lib/sandbox.rb', line 40 def self.scoop! self.cleanup! end |