Skip to content

Instantly share code, notes, and snippets.

@mistrikushal
Created January 10, 2017 10:42
Show Gist options
  • Save mistrikushal/d3c45551799b42edb6d41e22d7447d3d to your computer and use it in GitHub Desktop.
Save mistrikushal/d3c45551799b42edb6d41e22d7447d3d to your computer and use it in GitHub Desktop.
practical test
COMMANDS = ['DEPEND', 'INSTALL', 'REMOVE', 'LIST']
@component_dependencies = Hash.new
@installed_components = Array.new
def validate_command(command)
command_size = command.size
command_name = command.split(' ').first
return false unless COMMANDS.include?(command_name)
return false if command_name != command_name.upcase
return false if command_size > 80
return true
end
def execute_command(command)
command_name = command.split(' ')[0]
command_in_array = command.split(' ')
component = command_in_array[1]
items = command_in_array.drop(2)
case command_name
when 'DEPEND'
create_dependency(component, items)
when 'INSTALL'
install_component(component, items)
when 'REMOVE'
remove_component(component)
when 'LIST'
list_components
end
end
def create_dependency(component, items)
@component_dependencies.merge!(component=> items)
print @component_dependencies
print "\n"
end
def install_component(component, items)
if !@component_dependencies.key?(component)
print "Installing #{component}\n"
@installed_components.push component
print @installed_components
print "\n"
else
@component_dependencies[component].each do |c|
if !@installed_components.include?(c)
print " Installing #{c} \n"
@installed_components.push c
else
next
end
#@installed_components.push
end
@installed_components.push component
print " Installing #{component}\n"
end
end
def remove_component(component)
if @installed_components.include?(component)
if @component_dependencies.key?(component)
print " Removing #{component}\n"
@installed_components.delete_if{|i|i== component}
else
component_usage = 0
@component_dependencies.keys.each do |c|
next unless @installed_components.include?(c)
if @component_dependencies[c].include?(component)
component_usage = component_usage + 1
end
end
if component_usage > 1
print " #{component} is still needed\n"
elsif component_usage == 1
@installed_components.delete_if{|i|i== component}
elsif component_usage == 0
print " #{component} is not installed\n"
end
end
else
print " #{component} is not installed. \n"
end
end
def list_components
@installed_components.each do |c|
print " #{c}"
print "\n"
end
end
print 'Enter command: '
print "\n"
while command = gets.chomp
command_name = command.split(' ')[0]
case command_name
when 'END'
break
when *COMMANDS
is_valid_command = validate_command(command)
print "Invalid Command!\n" unless is_valid_command
if is_valid_command
print command+"\n" unless command_name.eql?('LIST')
execute_command(command)
end
else
print "Invalid Command!\n"
break
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment