Class: LFA::Router::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/LFA/router/config.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tree, dirname) ⇒ Config

Returns a new instance of Config.



22
23
24
25
26
27
28
# File 'lib/LFA/router/config.rb', line 22

def initialize(tree, dirname)
  # TODO: path-method-to-function cache
  raise "functions is not specified" unless tree[:functions]
  raise "resources is not specified" unless tree[:resources]
  @functions = Hash[*(tree[:functions].map{|f| Function.new(f, dirname) }.map{|f| [f.name, f] }.flatten)]
  @resources = tree[:resources].map{|r| Resource.new(r, @functions) }
end

Instance Attribute Details

#functionsObject (readonly)

Returns the value of attribute functions.



12
13
14
# File 'lib/LFA/router/config.rb', line 12

def functions
  @functions
end

#resourcesObject (readonly)

Returns the value of attribute resources.



12
13
14
# File 'lib/LFA/router/config.rb', line 12

def resources
  @resources
end

Class Method Details

.parse(yaml_filename) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/LFA/router/config.rb', line 14

def self.parse(yaml_filename)
  tree = File.open(yaml_filename) do |file|
    YAML.load(file.read, symbolize_names: true, aliases: true)
  end
  dirname = File.dirname(File.absolute_path(yaml_filename))
  Config.new(tree, dirname)
end

Instance Method Details

#dig(path, method) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/LFA/router/config.rb', line 30

def dig(path, method)
  raise "invalid path" unless path.start_with?("/")
  parts = if path == "/"
            ["/"]
          else
            path.split("/").filter{|str| str.size > 0 }.map{|part| "/" + part}
          end
  resource = self
  path_parameters = {}
  parts.each_with_index do |part, index|
    resource = resource.resources.find{|r| r.is_wildcard? || r.path == part }
    if resource
      if resource.is_wildcard? && resource.is_greedy_wildcard?
        path_parameters[resource.parameter_name] = (parts[index..-1].join)[1..-1] # omit heading '/'
        break
      elsif resource.is_wildcard?
        path_parameters[resource.parameter_name] = part[1..-1] # omit heading '/'
      end
    else # resource == nil
      break
    end
  end
  if resource
    if resource.is_greedy_wildcard?
      MatchedFunction.new(
        function: resource.methods.fetch(:ANY),
        path_parameters: path_parameters,
      )
    else
      func = resource.methods[method.to_sym]
      if func
        MatchedFunction.new(
          function: func,
          path_parameters: path_parameters.size > 0 ? path_parameters : nil,
        )
      else
        nil
      end
    end
  else
    nil # when the resource is not found
  end
end