class Rrant::Store

Public: Handles local storage using PStore and directory structure initialization. Serializes given rants for proper storage.

Attributes

images[R]
root[R]
store[R]

Public Class Methods

new(path = nil) click to toggle source

Constructor: Initializes directories and store.

path - Integer, directory where we want to store our rants/images

# File lib/rrant/store.rb, line 16
def initialize(path = nil)
  path = path || Dir.home
  raise Error::InvalidPath unless Dir.exist?(path)

  @root = "#{path}/.rrant"
  @images = "#{@root}/images/"

  initialize_directories
  initialize_store
end

Public Instance Methods

add(rants) click to toggle source

Public: Adds serialized rants as 'entities' and 'ids' to the store.

# File lib/rrant/store.rb, line 28
def add(rants)
  @store.transaction do
    @store[:ids] += build_ids(rants)
    @store[:entities] += build_entities(rants)
  end
end
empty?() click to toggle source
# File lib/rrant/store.rb, line 35
def empty?
  ids.empty?
end
touch(rant_id) click to toggle source

Public: Finds rant with given ID and updates its 'viewed_at' parameter.

# File lib/rrant/store.rb, line 47
def touch(rant_id)
  @store.transaction do
    @store[:entities] = @store[:entities].map do |rant|
      rant['viewed_at'] = DateTime.now if rant['id'] == rant_id
      rant
    end
  end
end

Private Instance Methods

build_entities(rants) click to toggle source
# File lib/rrant/store.rb, line 76
def build_entities(rants)
  rants.map { |rant| inject_rant(rant) }
end
build_ids(rants) click to toggle source
# File lib/rrant/store.rb, line 72
def build_ids(rants)
  rants.map { |rant| rant['id'] }
end
image_for(rant) click to toggle source

Private: Adds 'attached_image' parameter to rant pointing to image stored in '@images' directory.

rant - Hash.

# File lib/rrant/store.rb, line 95
def image_for(rant)
  return nil if image_blank?(rant)

  @images + rant['attached_image']['url'].split('/')[-1]
end
initialize_directories() click to toggle source

Private: Creates directory structure if there isn't one.

# File lib/rrant/store.rb, line 59
def initialize_directories
  Dir.mkdir(@root) unless Dir.exist?(@root)
  Dir.mkdir(@images) unless Dir.exist?(@images)
end
initialize_store() click to toggle source

Private: Initializes PStore to '@store' variable. If there are no 'ids' or 'entities' in store, it creates them.

# File lib/rrant/store.rb, line 66
def initialize_store
  @store = PStore.new("#{@root}/store.pstore")
  !ids && initialize_ids
  !entities && initialize_entities
end
inject_rant(rant) click to toggle source

Private: Adds additional parameters to rant.

rant - Hash.

# File lib/rrant/store.rb, line 83
def inject_rant(rant)
  rant.tap do |injected|
    injected['created_at'] = DateTime.now
    injected['viewed_at'] = injected['viewed_at'] || nil
    injected['image'] = image_for(injected)
  end
end