Class: NwsOpenapiSdk::PathParser

Inherits:
Object
  • Object
show all
Defined in:
lib/nws_openapi_sdk/path_parser.rb

Overview

Class must be called by ‘.parse’. Calling ‘.parse(path, *kwargs)’, where ‘path’ is a NWS API url path and ‘*kwargs’ are the url segment variables in that path. This will replace the segment placeholders with the kwargs. example:

NwsOpenapiSdk::PathParser.parse(

'/icons/{set}/{timeOfDay}',
{ set: x, timeOfDay: 1400 }

)

> ‘/icons/x/400’

This class is not designed to be used more that once.

Constant Summary collapse

SLASH =
'/'
COMMA =
','
LEFT_CURLY_BRACE =
'{'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, **kwargs) ⇒ PathParser

Returns a new instance of PathParser.



30
31
32
33
34
35
# File 'lib/nws_openapi_sdk/path_parser.rb', line 30

def initialize(path, **kwargs)
  @segments = path.split(SLASH).reject(&:empty?)
  # ['icons', '{set}', '{timeOfDay}', '{first}', '{second}']
  # ['gridpoints', '{wfo}', '{x},{y}', 'forecast']
  @kwargs = kwargs.transform_values(&:to_s)
end

Instance Attribute Details

#kwargsObject (readonly)

Returns the value of attribute kwargs.



18
19
20
# File 'lib/nws_openapi_sdk/path_parser.rb', line 18

def kwargs
  @kwargs
end

#segmentsObject (readonly)

Returns the value of attribute segments.



18
19
20
# File 'lib/nws_openapi_sdk/path_parser.rb', line 18

def segments
  @segments
end

Class Method Details

.parse(path, **kwargs) ⇒ Object



26
27
28
# File 'lib/nws_openapi_sdk/path_parser.rb', line 26

def self.parse(path, **kwargs)
  new(path, **kwargs).parse
end

Instance Method Details

#parseObject



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/nws_openapi_sdk/path_parser.rb', line 37

def parse
  segments.each_with_object(String.new) do |segment, uri|
    uri << SLASH
    uri << if segment.include?(COMMA) # '{x},{y}'
             comma_separate_vars(segment).join(COMMA)
           elsif segment[0] == LEFT_CURLY_BRACE # '{wfo}'
             mapped_kwarg(segment)
           else # 'gridpoints'
             segment
           end
  end
end