Class: Adapter

Inherits:
Object
  • Object
show all
Defined in:
lib/adapters/Adapter.rb

Direct Known Subclasses

Sync

Instance Method Summary collapse

Constructor Details

#initialize(file_path, js_var) ⇒ Adapter

Returns a new instance of Adapter.



3
4
5
6
7
8
9
10
# File 'lib/adapters/Adapter.rb', line 3

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 format.

Find the format of a file based on its extension.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/adapters/Adapter.rb', line 36

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) ⇒ Object

Normalize path.

Parameters:

  • file_path
    • An absolute or relative path.

Returns:

  • An absolute path.



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/adapters/Adapter.rb', line 18

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.

Parameters:

  • String

    json



79
80
81
82
83
84
85
86
87
# File 'lib/adapters/Adapter.rb', line 79

def unwrap(json)

  # Deletes: var data = \"
  json.delete_prefix!(@prefix + '"')

  # Deletes: \";
  json.delete_suffix!('"' + @suffix)

end

#wrapObject

Wrap JSON in a Javascript variable.

Parameters:

  • String

    json



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/adapters/Adapter.rb', line 56

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