Initial commit

This commit is contained in:
Senad Uka
2018-08-13 11:25:01 +02:00
commit de58457ef9
10 changed files with 195 additions and 0 deletions

23
lib/api/app.rb Normal file
View File

@@ -0,0 +1,23 @@
require 'json'
require 'sinatra/base'
require_relative '../http/query'
module Pruning
module API
class App < Sinatra::Base
before { content_type :json }
after { serialise_response }
private
def serialise_response
return unless content_type == 'application/json'
response.body = [JSON(response.body)]
end
def query
Pruning::HTTP::Query.new(params)
end
end
end
end

17
lib/api/tree.rb Normal file
View File

@@ -0,0 +1,17 @@
require 'rest-client'
require_relative 'app'
require_relative '../repos/tree'
require_relative '../pruner'
module Pruning
module API
class Tree < App
get '/tree/:name' do
tree_repo = Pruning::Repos::Tree.new(RestClient, ENV['TREE_SOURCE_API_HOSTNAME'])
complete_tree = tree_repo.get(query.name)
pruner = Pruning::Processing::Pruner.new(complete_tree)
pruner.prune_tree(query.indicator_ids)
end
end
end
end

18
lib/http/query.rb Normal file
View File

@@ -0,0 +1,18 @@
module Pruning
module HTTP
class Query < Struct.new(:name, :indicator_ids)
def initialize(params = {})
values = members.map do |member|
value = params.fetch(member, nil)
next if value.nil?
case member
when :indicator_ids then value.map(&:to_i) # break on purpose if indicator_ids is not an array
when :name then value.to_s.gsub(/[^A-Za-z]/,'')
else value
end
end
super(*values)
end
end
end
end

32
lib/pruner.rb Normal file
View File

@@ -0,0 +1,32 @@
module Pruning
module Processing
class Pruner
def initialize(tree, indicator_ids)
@tree = tree
end
def prune_tree(nodes, indicator_ids)
nodes.delete_if do |node|
unwanted_indicator = indicator_node?(node) && !indicator_ids.include?(node['id'])
has_no_wanted_indicators_in_children = prune_tree(children(node), indicator_ids)
unwanted_indicator && has_no_wanted_indicators_in_children
end
nodes.empty?
end
private
def children(node)
node.get('sub-themes', false) ||
node.get('categories', false) ||
node.get('indicators', false) ||
[]
end
def indicator_node?(node)
children(node).empty?
end
end
end
end

24
lib/repos/tree.rb Normal file
View File

@@ -0,0 +1,24 @@
require 'rest-client'
require 'retries'
require 'json'
module Pruning
module Repos
class Tree
def initialize(client=RestClient, base_url)
@client = client
@base_url = base_url
end
def get(name)
resp = @client.get(url(name))
JSON(resp.body)
end
private
def url(name)
"#{@base_url}/tree/#{name}"
end
end
end
end