Module: Ruson::Persistence
- Included in:
- Base
- Defined in:
- lib/ruson/persistence.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
- #delete_file_from_disk ⇒ Object
- #destroy ⇒ Object
- #ensure_model_folder_exists ⇒ Object
- #generate_uniq_id ⇒ Object
- #model_path ⇒ Object
- #save ⇒ Object
- #update(attributes) ⇒ Object
- #write_file_to_disk ⇒ Object
Class Method Details
.included(klass) ⇒ Object
3 4 5 6 |
# File 'lib/ruson/persistence.rb', line 3 def self.included(klass) klass.extend(ClassMethods) klass.extend(Ruson::Json) end |
Instance Method Details
#delete_file_from_disk ⇒ Object
20 21 22 |
# File 'lib/ruson/persistence.rb', line 20 def delete_file_from_disk FileUtils.rm_f(model_path) end |
#destroy ⇒ Object
24 25 26 27 |
# File 'lib/ruson/persistence.rb', line 24 def destroy delete_file_from_disk true end |
#ensure_model_folder_exists ⇒ Object
29 30 31 32 33 |
# File 'lib/ruson/persistence.rb', line 29 def ensure_model_folder_exists return if File.exist?(self.class.model_base_path) FileUtils.mkdir_p(self.class.model_base_path) end |
#generate_uniq_id ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/ruson/persistence.rb', line 35 def generate_uniq_id ensure_model_folder_exists return if id id = 0 Dir.glob(File.join(self.class.model_base_path, '*.json')).each do |path| file_id = id_from_file_path(path) id = file_id if file_id > id end self.id = id + 1 end |
#model_path ⇒ Object
51 52 53 |
# File 'lib/ruson/persistence.rb', line 51 def model_path File.join(self.class.model_base_path, "#{id}.json") end |
#save ⇒ Object
61 62 63 64 65 66 |
# File 'lib/ruson/persistence.rb', line 61 def save self.class.ensure_output_folder_is_defined generate_uniq_id write_file_to_disk true end |
#update(attributes) ⇒ Object
68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/ruson/persistence.rb', line 68 def update(attributes) attributes.symbolize_keys! # Takes only accessor for attributes to be updated, avoiding to nullify # the other attributes. filtered_accessors = self.class.accessors.select do |key, accessor_attrs| attributes.key?(key) || attributes.key?(accessor_attrs[:name]) end update_attributes(filtered_accessors, attributes) save end |
#write_file_to_disk ⇒ Object
55 56 57 58 59 |
# File 'lib/ruson/persistence.rb', line 55 def write_file_to_disk File.open(model_path, 'w') do |file| file.write(to_json(exclude: %i[id])) end end |