Class: MightyStruct
- Inherits:
-
Object
- Object
- MightyStruct
- Defined in:
- lib/mighty_struct.rb,
lib/mighty_struct/version.rb
Constant Summary collapse
- VERSION =
"0.1.4"
Class Method Summary collapse
- .new?(object) ⇒ Boolean
-
.to_object(object) ⇒ Object
in order not to pollute the instance’s method namespace this is a class method.
Instance Method Summary collapse
-
#initialize(object, options = {}) ⇒ MightyStruct
constructor
A new instance of MightyStruct.
-
#method_missing(method_name, *arguments, &block) ⇒ Object
last line of defense.
- #respond_to_missing?(method_name, include_private = false) ⇒ Boolean
Constructor Details
#initialize(object, options = {}) ⇒ MightyStruct
Returns a new instance of MightyStruct.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/mighty_struct.rb', line 13 def initialize(object, = {}) unless self.class.new?(object) raise ArgumentError.new("Cannot create a an instance of #{self.class} for the given object!") end @cache = {} @cache_mode = [:caching] || :enabled if (@object = object).respond_to?(:keys) object.keys.each do |_key| unless respond_to?(_key) define_singleton_method(_key) do if @cache_mode == :disabled self.class.new?(value = @object[_key]) ? self.class.new(value) : value else @cache[_key] ||= self.class.new?(value = @object[_key]) ? self.class.new(value) : value end end end end end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *arguments, &block) ⇒ Object
last line of defense
39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/mighty_struct.rb', line 39 def method_missing(method_name, *arguments, &block) if @object.respond_to?(method_name) @cache.clear if @cache_mode == :smart # clear the properties cache if we are smart result = @object.send(method_name, *arguments, &block) # ensure that results of called methods are mighty structs again self.class.new?(result) ? self.class.new(result) : result else super end end |
Class Method Details
.new?(object) ⇒ Boolean
4 5 6 |
# File 'lib/mighty_struct.rb', line 4 def self.new?(object) object.is_a?(Enumerable) end |
.to_object(object) ⇒ Object
in order not to pollute the instance’s method namespace this is a class method
9 10 11 |
# File 'lib/mighty_struct.rb', line 9 def self.to_object(object) object.is_a?(self) ? object.instance_variable_get(:@object) : object end |
Instance Method Details
#respond_to_missing?(method_name, include_private = false) ⇒ Boolean
51 52 53 |
# File 'lib/mighty_struct.rb', line 51 def respond_to_missing?(method_name, include_private = false) @object.respond_to?(method_name) || super end |