Class: Filebase::Drivers::JSON

Inherits:
Object
  • Object
show all
Includes:
Mixin
Defined in:
lib/filebase/drivers/json.rb

Instance Method Summary collapse

Methods included from Mixin

#count, #delete, #has_key?, #keys, #path, #root

Constructor Details

#initialize(root) ⇒ JSON

Returns a new instance of JSON.



10
11
12
13
# File 'lib/filebase/drivers/json.rb', line 10

def initialize( root )
  super
  @extension = "json"
end

Instance Method Details

#allObject



15
16
17
18
19
20
21
# File 'lib/filebase/drivers/json.rb', line 15

def all
   Dir["#{@root}/*.json"].map do |file|
     obj = File.open(file) { |f| ::JSON.load(f) }
     obj['key'] = File.basename(file, '.json') if obj.is_a? Hash
     obj or nil
   end
end

#find(key) ⇒ Object



23
24
25
26
27
# File 'lib/filebase/drivers/json.rb', line 23

def find( key )
   obj = File.open( path(key) ) { |f| ::JSON.load(f) } rescue nil
	obj['key'] = key if obj.is_a? Hash
	obj or nil # convert false to nil
end

#find_keys(keys) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/filebase/drivers/json.rb', line 29

def find_keys(keys)
  keys.map do |key|
    obj = File.open( path(key) ) { |f| ::JSON.load(f) } rescue nil
		obj['key'] = key if obj.is_a? Hash
		obj or nil # convert false to nil
  end
end

#write(key, hash) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/filebase/drivers/json.rb', line 37

def write( key, hash )
   File.open(path(key), "w") do |f|
     begin
       f.puts ::JSON.pretty_generate(hash)
       true
     rescue
       nil
     end
   end
end