Sha256: f6b5fca2c0db017ce11074c37ac032adba91cdb155215d635bf4c96e1fe4daad

Contents?: true

Size: 1.74 KB

Versions: 5

Compression:

Stored size: 1.74 KB

Contents

module MasterView
  module ParserHelpers
    #returns an array of args by parsing and evaling the str value passed in
    #uses evaling, so can't have any variables only simple strings, numbers, booleans
    def parse_eval_into_array(value)
      return [] if value.nil? || value.empty?
      val = value.strip
      args = []
      until val.empty?
        if val =~ /^[:'"%\[{&*]/ #starts with quote or ruby lang char
          v = nil
          val = '{'+val+'}' if val =~ /^:/ #starts with colon, assume hash so wrap with brackets
          eval 'v = '+ val #rest is all evaled
          if v.is_a? Array
            args += v
          else 
            args << v
          end
          break
        else
          unquoted_string = val.slice!( /^[^,]+/ ) #pull off everything up to a comma
          unquoted_string.strip!
          args.push unquoted_string
          val.slice!( /^,/ ) #strip off comma if exists
          val.strip!
        end
      end
      args
    end

    #returns a hash, for values that are not already part of hash it adds them using default_key
    #uses evaling so it cannot have any variables or non-simple types
    def parse_eval_into_hash(value, default_key)
      h = {}
      a = parse_eval_into_array(value)
      a.each do |v|
        if v.is_a?(Hash)
          h.merge!(v)
        else #it adds any additional non-hash args using default key, if key,val exists, it changes to array and appends
          prev = h[default_key]
          if prev.nil? #nil just add it
            h[default_key] = v
          elsif prev.is_a?(Array) #was array, concat
            h[default_key] = prev+v
          else #anything else, make it into array
            h[default_key] = [prev, v]
          end
        end
      end
      h
    end

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
masterview-0.3.3 lib/masterview/parser_helpers.rb
masterview-0.3.0 lib/masterview/parser_helpers.rb
masterview-0.3.1 lib/masterview/parser_helpers.rb
masterview-0.3.2 lib/masterview/parser_helpers.rb
masterview-0.3.4 lib/masterview/parser_helpers.rb