class Timeline

Public Class Methods

exist?() click to toggle source
# File lib/self_logger/timeline.rb, line 35
def self.exist?
  File.exist?(Timeline.store_path)
end
init() click to toggle source
# File lib/self_logger/timeline.rb, line 39
def self.init
  File.open(Timeline.store_path, 'w') do |f|
    f.puts('[]')
  end
end
new() click to toggle source
# File lib/self_logger/timeline.rb, line 8
def initialize
  json = load_json!
  posts = convert_posts(json)
  @posts = posts
end

Private Class Methods

store_path() click to toggle source
# File lib/self_logger/timeline.rb, line 76
def self.store_path
  dir = ENV['SELF_LOGGER_DIR'] || './'

  "#{dir}/posts.json"
end

Public Instance Methods

add(post) click to toggle source
# File lib/self_logger/timeline.rb, line 18
def add(post)
  @posts.append(post)
  save
end
index() click to toggle source
# File lib/self_logger/timeline.rb, line 14
def index
  @posts
end
remove() click to toggle source
# File lib/self_logger/timeline.rb, line 23
def remove; end
to_json(*_args) click to toggle source
# File lib/self_logger/timeline.rb, line 29
def to_json(*_args)
  JSON.pretty_generate(
    @posts.map(&:to_h)
  )
end
to_s(format = nil) click to toggle source
# File lib/self_logger/timeline.rb, line 25
def to_s(format = nil)
  @posts.map{ |post| post.to_s(format) }.join("\n")
end

Private Instance Methods

convert_posts(json) click to toggle source
# File lib/self_logger/timeline.rb, line 70
def convert_posts(json)
  json.map { |post| Post.new(post) }
rescue ArgumentError
  raise RuntimeError.new('invalid json format')
end
load_json!() click to toggle source
# File lib/self_logger/timeline.rb, line 57
def load_json!
  unless File.exist?(Timeline.store_path)
    raise RuntimeError.new('json not found')
  end

  File.open(Timeline.store_path) do |f|
    JSON.parse(f.read, symbolize_names: true)
  end

rescue JSON::ParserError
  raise RuntimeError.new('invalid json')
end
save() click to toggle source
# File lib/self_logger/timeline.rb, line 51
def save
  File.open(Timeline.store_path, 'w') do |f|
    f.puts(to_json)
  end
end
symbolize_keys(hash) click to toggle source
# File lib/self_logger/timeline.rb, line 47
def symbolize_keys(hash)
  hash.transform_keys(&:to_sym)
end