Class: Hbtrack::Importer::HbtrackImporter

Inherits:
AbstractImporter show all
Defined in:
lib/hbtrack/importer/hbtrack_importer.rb

Constant Summary collapse

Habit =
Hbtrack::Database::Habit
Entry =
Hbtrack::Database::Entry
ENTRY_TYPE =
{
  '0' => 'missed',
  '1' => 'completed',
  ' ' => 'skip'
}

Instance Method Summary collapse

Methods inherited from AbstractImporter

#store_in

Constructor Details

#initializeHbtrackImporter

Returns a new instance of HbtrackImporter.



19
20
21
22
# File 'lib/hbtrack/importer/hbtrack_importer.rb', line 19

def initialize
  super
  @index = 1
end

Instance Method Details

#create_entries_of(id, entries) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/hbtrack/importer/hbtrack_importer.rb', line 52

def create_entries_of(id, entries)
  @entries[id] = entries.flat_map do |entry|
    month, values = entry.split(': ')

    values.split("").map.with_index(1) do |value, index|
      create_entry(month, index, value)
    end
  end
end

#create_entry(month, day, value) ⇒ Object



62
63
64
65
66
# File 'lib/hbtrack/importer/hbtrack_importer.rb', line 62

def create_entry(month, day, value)
  timestamp = create_timestamp_for(month, day)
  type = ENTRY_TYPE[value]
  Entry.new(timestamp, type)
end

#create_habit(habit) ⇒ Object

Create a Habit



46
47
48
49
50
# File 'lib/hbtrack/importer/hbtrack_importer.rb', line 46

def create_habit(habit)
  habit = Habit.new(habit, @index)
  @index += 1
  habit
end

#create_timestamp_for(month, day) ⇒ Object



68
69
70
71
72
# File 'lib/hbtrack/importer/hbtrack_importer.rb', line 68

def create_timestamp_for(month, day)
  year, month = month.split(',').map(&:to_i)
  time_zone = Time.new.zone
  DateTime.new(year, month, day, 0, 0, 0, "#{time_zone}:00").to_s
end

#extract_from(id, collection) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/hbtrack/importer/hbtrack_importer.rb', line 35

def extract_from(id, collection)
  arr = collection.split("\n")

  # Get habit name
  habit_name = arr.shift
  @habits[id] = create_habit(habit_name)

  create_entries_of(id, arr)
end

#import_from(file) ⇒ Object

Import and parse the CSV from Streaks



25
26
27
28
29
30
31
32
33
# File 'lib/hbtrack/importer/hbtrack_importer.rb', line 25

def import_from(file)
  raise 'File not found' unless File.exist?(file)
  input = File.read(file).split(/\n\n/)
  input.each_with_index do |collection, index|
    extract_from(index, collection)
  end

  [@habits, @entries]
end