Module: Structure::ClassMethods
- Defined in:
- lib/structure/double.rb,
lib/structure/class_methods.rb
Instance Attribute Summary collapse
-
#attribute_names ⇒ Object
readonly
Returns an array of attribute names as strings.
Class Method Summary collapse
Instance Method Summary collapse
- #attribute(name, &block) ⇒ Object
-
#double ⇒ Object
Creates a double that mocks a value object built with Structure during a test.
Instance Attribute Details
#attribute_names ⇒ Object (readonly)
Returns an array of attribute names as strings
6 7 8 |
# File 'lib/structure/class_methods.rb', line 6 def attribute_names @attribute_names end |
Class Method Details
.extended(base) ⇒ Object
8 9 10 11 |
# File 'lib/structure/class_methods.rb', line 8 def self.extended(base) base.instance_variable_set :@attribute_names, [] base.send :__overwrite_initialize end |
Instance Method Details
#attribute(name, &block) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/structure/class_methods.rb', line 13 def attribute(name, &block) name = name.to_s if name.end_with?('?') name = name.chop module_eval " def \#{name}?\n \#{name}\n end\n CODE\n end\n\n module_eval <<-CODE, __FILE__, __LINE__ + 1\n def \#{name}\n @__mutex.synchronize {\n break if @__table.key?(\"\#{name}\")\n\n @__table[\"\#{name}\"] = __\#{name}\n @__table[\"\#{name}\"].freeze\n\n @__table[\"\#{name}\"]\n }\n\n @__table[\"\#{name}\"]\n end\n CODE\n\n define_method \"__\#{name}\", block\n private \"__\#{name}\"\n\n @attribute_names << name\n\n name.to_sym\nend\n", __FILE__, __LINE__ + 1 |
#double ⇒ Object
Creates a double that mocks a value object built with Structure during a test
The double has an alternative constructor that takes a hash to set values. Otherwise, it shares the public API of the mocked value object.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/structure/double.rb', line 10 def double klass = Class.new(self) (private_instance_methods(false) + protected_instance_methods(false) - [:initialize]).each do |name| klass.send :undef_method, name end klass.module_eval do def initialize(values = {}) values.each do |key, value| instance_variable_set :"@#{key}", value end end attribute_names.each do |name| module_eval " private def __\#{name}\n @\#{name}\n end\n CODE\n end\n\n module_eval(&Proc.new) if block_given?\n end\n\n class << klass\n undef_method :double\n end\n\n klass\nend\n", __FILE__, __LINE__ + 1 |