Class: ErpRules::RulesEngine::Context
- Inherits:
-
OpenStruct
- Object
- OpenStruct
- ErpRules::RulesEngine::Context
- Defined in:
- lib/erp_rules/rules_engine/context.rb
Overview
OpenStruct is part of ruby stdlib This class adds methods to allow hash-like behavior
Instance Method Summary collapse
- #[](key) ⇒ Object
-
#[]=(key, *args) ⇒ Object
This will set a method on the struct using array syntax.
-
#initialize(hash = nil) ⇒ Context
constructor
A new instance of Context.
-
#method_missing(mid, *args) ⇒ Object
need this method in order to mimic []= behavior using the method/attr syntax of OpenStruct.
Constructor Details
#initialize(hash = nil) ⇒ Context
Returns a new instance of Context.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/erp_rules/rules_engine/context.rb', line 11 def initialize(hash=nil) if hash hash.each do |k,v| if v.class == Hash result = ErpRules::RulesEngine::Context.new(v) hash[k] = result elsif v.class == Array v.map! do |item| #ostruct requires objects passed to it on the constructr #to support #each if item.is_a? Enumerable ErpRules::RulesEngine::Context.new(item) else item end end #end Array case end end end super(hash) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(mid, *args) ⇒ Object
need this method in order to mimic []= behavior using the method/attr syntax of OpenStruct
56 57 58 59 60 61 |
# File 'lib/erp_rules/rules_engine/context.rb', line 56 def method_missing(mid, *args) if args[0].class == Hash args[0] = ErpRules::RulesEngine::Context.new(args[0]) end super(mid, *args) end |
Instance Method Details
#[](key) ⇒ Object
34 35 36 |
# File 'lib/erp_rules/rules_engine/context.rb', line 34 def [](key) send(key) end |
#[]=(key, *args) ⇒ Object
This will set a method on the struct using array syntax. Trying to set the argument in eval led to an error, hence the ‘send’ call following it.
43 44 45 46 47 48 49 50 51 52 |
# File 'lib/erp_rules/rules_engine/context.rb', line 43 def []=(key, *args) arg = args[0] eval("#{key} = nil", binding) if arg.class == Hash send("#{key}=", ErpRules::RulesEngine::Context.new(arg)) else send("#{key}=", arg) end end |