Class: Hub::GitHubAPI::FileStore

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/hub/github_api.rb

Overview

Filesystem store suitable for Configuration

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ FileStore

Returns a new instance of FileStore.



452
453
454
455
456
457
# File 'lib/hub/github_api.rb', line 452

def initialize filename
  @filename = filename
  @data = Hash.new {|d, host| d[host] = [] }
  @persist_next_change = false
  load if File.exist? filename
end

Instance Method Details

#fetch_value(host, user, key) ⇒ Object



459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/hub/github_api.rb', line 459

def fetch_value host, user, key
  entries = get(host)
  entries << {} if entries.empty?
  entry = entries.first
  entry.fetch(key.to_s) {
    value = yield
    raise "no value for key :#{key}" if value.nil? || value.empty?
    entry[key.to_s] = value
    save_if_needed
    value
  }
end

#loadObject



481
482
483
484
# File 'lib/hub/github_api.rb', line 481

def load
  existing_data = File.read(@filename)
  @data.update yaml_load(existing_data) unless existing_data.strip.empty?
end

#mkdir_p(dir) ⇒ Object



491
492
493
494
495
496
497
# File 'lib/hub/github_api.rb', line 491

def mkdir_p(dir)
  dir.split('/').inject do |parent, name|
    d = File.join(parent, name)
    Dir.mkdir(d) unless File.exist?(d)
    d
  end
end

#persist_next_change!Object



472
473
474
# File 'lib/hub/github_api.rb', line 472

def persist_next_change!
  @persist_next_change = true
end

#saveObject



486
487
488
489
# File 'lib/hub/github_api.rb', line 486

def save
  mkdir_p File.dirname(@filename)
  File.open(@filename, 'w', 0600) {|f| f << yaml_dump(@data) }
end

#save_if_neededObject



476
477
478
479
# File 'lib/hub/github_api.rb', line 476

def save_if_needed
  @persist_next_change && save
  @persist_next_change = false
end

#yaml_dump(data) ⇒ Object



519
520
521
522
523
524
525
526
527
528
529
530
531
532
# File 'lib/hub/github_api.rb', line 519

def yaml_dump(data)
  yaml = ['---']
  data.each do |host, values|
    yaml << "#{host}:"
    values.each do |hash|
      dash = '-'
      hash.each do |key, value|
        yaml << "#{dash} #{key}: #{value}"
        dash = ' '
      end
    end
  end
  yaml.join("\n")
end

#yaml_load(string) ⇒ Object



499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/hub/github_api.rb', line 499

def yaml_load(string)
  hash = {}
  host = nil
  string.split("\n").each do |line|
    case line
    when /^---\s*$/, /^\s*(?:#|$)/
      # ignore
    when /^(.+):\s*$/
      host = hash[$1] = []
    when /^([- ]) (.+?): (.+)/
      key, value = $2, $3
      host << {} if $1 == '-'
      host.last[key] = value.gsub(/^'|'$/, '')
    else
      raise "unsupported YAML line: #{line}"
    end
  end
  hash
end