Class: Rowdb::Adapter
- Inherits:
-
Object
- Object
- Rowdb::Adapter
- Defined in:
- lib/adapters/adapter.rb
Direct Known Subclasses
Instance Method Summary collapse
-
#find_format(file_path) ⇒ Object
Find the format of a file based on its extension.
-
#initialize(file_path, js_var) ⇒ Adapter
constructor
A new instance of Adapter.
-
#normalize_path(file_path) ⇒ String
Normalize path to absolute path.
-
#unwrap(json) ⇒ Object
Unwrap JSON from a Javascript variable.
-
#wrap ⇒ Object
Wrap JSON in a Javascript variable.
Constructor Details
#initialize(file_path, js_var) ⇒ Adapter
Returns a new instance of Adapter.
4 5 6 7 8 9 10 11 |
# File 'lib/adapters/adapter.rb', line 4 def initialize(file_path, js_var) @source = normalize_path(file_path) @format = find_format(file_path) @prefix = "var #{js_var} = " @suffix = ";" end |
Instance Method Details
#find_format(file_path) ⇒ Object
Find the format of a file based on its extension.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/adapters/adapter.rb', line 37 def find_format(file_path) extension = File.extname(file_path) case extension when ".json" return :json when ".js" return :js end :json end |
#normalize_path(file_path) ⇒ String
Normalize path to absolute path.
19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/adapters/adapter.rb', line 19 def normalize_path(file_path) # Absolute path. if file_path.start_with? '/' return file_path # Relative path. else # Get directory the script executed from. return File.join(Dir.pwd, '/' + file_path) end end |
#unwrap(json) ⇒ Object
Unwrap JSON from a Javascript variable.
80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/adapters/adapter.rb', line 80 def unwrap(json) # Deletes: var data = \" json.delete_prefix!(@prefix + '"') # Deletes: \"; # Deletes: \";\n json.delete_suffix!('"' + @suffix) json.delete_suffix!('"' + @suffix + "\n") end |
#wrap ⇒ Object
Wrap JSON in a Javascript variable.
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/adapters/adapter.rb', line 57 def wrap() new_file = "" # Open file. File.open(@source, 'r') do |file| new_file = file.read new_file.prepend(@prefix) new_file << @suffix end # Overwrite file. File.open(@source, 'w') do |file| file.write(new_file) end end |