Skip to content

Instantly share code, notes, and snippets.

@adammcarth
Created June 11, 2014 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adammcarth/0f969b18953142e7caef to your computer and use it in GitHub Desktop.
Save adammcarth/0f969b18953142e7caef to your computer and use it in GitHub Desktop.
This algorithm seems really ignorant... any suggestions?
class JTask
# JTask.find()
# Retrieves records from the database file.
# --------------------------------------------------------------------------------
# Eg: JTask.find("test.json", 1) || JTask.find("test.json", first: 10)
# #=> <JTask id=x, ...>
# --------------------------------------------------------------------------------
# See wiki guide for more usage examples...
# https://github.com/adammcarthur/jtask/wiki/find
def self.find(file, id=nil, dir=nil)
# Start off by setting some variables and performing validations...
JTask::Helpers.validate_id(id)
@file_directory = JTask::Helpers.set_directory(dir)
@database = File.join(@file_directory, file)
JTask::Helpers.validate_file(@database)
@records = JSON.parse(File.read(@database))
# Return nil if there are no records in the database
return nil if @records.empty?
# [Integer] Look for the unique id in the database
if id.is_a?(Integer)
# we should return nil if the record doesn't exist...
return nil unless @records["#{id}"]
# ...load the single record to the results
results = JTask.new({ "id" => id.to_i }.merge(@records["#{id}"]))
end
# [Array] We need to find a number of records with their unique id
if id.is_a?(Array)
results = Array.new
id.each do |unique_id|
if @records["#{unique_id}"] # used so that only records that exist are added to the results
results << JTask.new({ "id" => unique_id.to_i }.merge(@records["#{unique_id}"]))
end
# Once again, return nil if it turns out that no id's
# in the array exist as a record in the database.
return nil if results.empty?
end
end
# [Hash] The first or last n records need to be found
if id.is_a?(Hash)
# Think of this more as `{first/last: number} do |key, value|`
id.each do |method, num|
if method.to_sym == :first
# get first `num` records
results = Hash[@records.to_a.first(num)]
elsif method.to_sym == :last
# get last `num` records (in reverse order)
results = Hash[@records.to_a.last(num).reverse]
end
end
# Finally, map each record to the results
results = results.map { |unique_id, record| JTask.new({ "id" => unique_id.to_i }.merge(record)) }
end
# [Symbol or nil] :all of the records need to be retrieved
if id.is_a?(Symbol) or id == nil
results = Array.new
@records.each do |unique_id, record|
results << JTask.new({ "id" => unique_id.to_i }.merge(record))
end
end
return results
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment