Sha256: a466d34a57c20242057a92d90d0716251b690330d18875b14bee516f57f7588a

Contents?: true

Size: 1.6 KB

Versions: 7

Compression:

Stored size: 1.6 KB

Contents

require 'ostruct'

module ErpRules
  module RulesEngine
    ##
    #OpenStruct is part of ruby stdlib
    #This class adds methods to allow hash-like
    #behavior
    class Context < OpenStruct

      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

      def [](key)
        send(key)
      end

      ##
      #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.
      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

      #need this method in order to mimic []= behavior
      #using the method/attr syntax of OpenStruct
      def method_missing(mid, *args)
        if args[0].class == Hash
          args[0] = ErpRules::RulesEngine::Context.new(args[0])
        end
        super(mid, *args)
      end

    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
erp_rules-4.2.0 lib/erp_rules/rules_engine/context.rb
erp_rules-4.0.0 lib/erp_rules/rules_engine/context.rb
erp_rules-3.1.0 lib/erp_rules/rules_engine/context.rb
erp_rules-3.0.4 lib/erp_rules/rules_engine/context.rb
erp_rules-3.0.3 lib/erp_rules/rules_engine/context.rb
erp_rules-3.0.2 lib/erp_rules/rules_engine/context.rb
erp_rules-3.0.1 lib/erp_rules/rules_engine/context.rb