Class: FsPlug
- Inherits:
-
Object
- Object
- FsPlug
- Defined in:
- lib/obvious/files/external/fs_plug.rb
Instance Method Summary collapse
- #find(input) ⇒ Object
- #get(input) ⇒ Object
-
#initialize(filename) ⇒ FsPlug
constructor
A new instance of FsPlug.
- #list ⇒ Object
- #load_data ⇒ Object
- #remove(input) ⇒ Object
- #save(input) ⇒ Object
- #save_data(input) ⇒ Object
Constructor Details
#initialize(filename) ⇒ FsPlug
Returns a new instance of FsPlug.
5 6 7 |
# File 'lib/obvious/files/external/fs_plug.rb', line 5 def initialize filename @filename = filename end |
Instance Method Details
#find(input) ⇒ Object
81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/obvious/files/external/fs_plug.rb', line 81 def find input data = [] query = load_data key = input.keys[0] query.each do |h| if input[key] == h[key] return h end end raise Exception.new 'no object found' end |
#get(input) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/obvious/files/external/fs_plug.rb', line 51 def get input data = [] query = load_data # transform the data if needed query.each do |h| return h if h[:id] == input[:id] end raise Exception.new 'no object found' end |
#list ⇒ Object
47 48 49 |
# File 'lib/obvious/files/external/fs_plug.rb', line 47 def list load_data end |
#load_data ⇒ Object
9 10 11 12 |
# File 'lib/obvious/files/external/fs_plug.rb', line 9 def load_data contents = File.read @filename JSON.parse contents, :symbolize_names => true end |
#remove(input) ⇒ Object
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/obvious/files/external/fs_plug.rb', line 63 def remove input data = [] # parse the json list query = load_data # transform the data if needed query.each do |h| unless h[:id] == input[:id] data << h end end save_data data # return true on success true end |
#save(input) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/obvious/files/external/fs_plug.rb', line 19 def save input data = [] query = load_data new_element = true if input[:id] == -1 # by convention set new element flag if id == -1 max_id = -1 # transform the data if needed query.each do |h| if input[:id] == h[:id] h = input end max_id = h[:id] if h[:id] > max_id data << h end # add data to the list if it's a new element if new_element input[:id] = max_id + 1 data << input end save_data data # return the transformed data input end |
#save_data(input) ⇒ Object
14 15 16 17 |
# File 'lib/obvious/files/external/fs_plug.rb', line 14 def save_data input json_data = JSON.pretty_generate input File.open(@filename, 'w') {|f| f.write(json_data) } end |