Skip to content

Instantly share code, notes, and snippets.

@adammcarth
Forked from universal/find.rb
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adammcarth/f78da8fb52f61c4184d0 to your computer and use it in GitHub Desktop.
Save adammcarth/f78da8fb52f61c4184d0 to your computer and use it in GitHub Desktop.
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_or_options, dir=nil)
do_something_with_the_file
case id_or_options
when Integer
self.find_by_id(file, id_or_options)
when Array
self.find_many(file, id_or_options)
when Hash
if keys.first.to_s == "first"
self.find_first(file, id_or_options)
elsif keys.first.to_s == "last"
self.find_last(file, id_or_options)
end
when :all or nil
self.find_all...
end
def self.find_by_id(..)
...
end
end
# lib/jtask/tasks/find_tasks.rb
class JTask
def self.find_by_id(hash, id)
if hash[id]
record = { "id" => id.to_i }.merge(hash[id])
return JTask.new(record)
else
return nil
end
end
def self.find_many(hash, id_array)
records = []
id_array.each do |id|
if hash[id]
record = { "id" => id.to_i }.merge(hash["#{id}"])
records << JTask.new(record)
end
end
return records
end
def self.find_first(hash, amount)
required_records = hash.to_a.first(amount)
records = []
required_records.each do |record|
record_hash = {"id" => record.key.to_i}.merge(record)
records << JTask.new(record_hash)
end
return records
end
def self.find_last(hash, amount)
required_records = hash.to_a.last(amount)
required_records = required_records.reverse
records = []
required_records.each do |record|
record_hash = {"id" => record.key.to_i}.merge(record)
records << JTask.new(record_hash)
end
return records
end
def self.find_all(hash)
records = []
hash.each do |record|
record_hash = {"id" => record.key.to_i}.merge(record)
records << record_hash
end
return records
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment