Method: ActiveFiles::Record::ClassMethods#find

Defined in:
lib/active_files/record.rb

#find(*args) ⇒ Object

Find. Tries way too hard to replicate ActiveRecord.

Find operates with three different retrieval mechanisms.

  • Find by name: Enter a name, or a glob. If one record can be found matching that name, then only one is returned. If more than one can be found, an array is returned. If no record can be found, ActiveFiles::FileNotFound is thrown.

  • Find first (:first): This will return the first record matched by the options used. If no record can matched, nil is returned.

  • Find all (:all: This will return all the records matched by the options used. If no records are found, an empty array is returned.

The last two approached accept an option hash as their last parameter. The options are:

  • :name => name

    Glob-based record name.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/active_files/record.rb', line 49

def find(*args)
  name = '*'
  order = nil

  if (args.length == 1 and args[0].kind_of?(String)) then
    name = args[0]
    mode = :name
  elsif (args.first == :first or args.first == :all)
    mode = args.first
    options = extract_find_options!(args)
    name = options[:name] if options.has_key?(:name)
    order = options[:order] if options.has_key?(:order)
  else
    raise ArgumentError, "Unknown mode: #{args.first}"
  end

  files = Dir[File.join(self.file_store, name + ActiveFiles.ext)]
  
  if files.empty? then
    case mode
    when :name
      raise ActiveFiles::FileNotFound
    when :first
      return nil
    when :all
      return Array.new()
    end
  elsif (mode == :first or (mode == :name and files.length == 1)) then
    return self.from_activefile(File.read(files.first), self.parse_file_id(files.first))
  else
    objs = Array.new()
    files.each do |file|
      objs.push(self.from_activefile(File.read(file), self.parse_file_id(file)))
    end

    return case order
           when 'asc' then objs.sort { |a,b| a.file_id <=> b.file_id }
           when 'desc' then objs.sort { |a,b| b.file_id <=> a.file_id }
           else objs
           end
  end
rescue Errno::ENOENT
  self.create_file_store
  self.find(*args)
end