Class: GSquire::Accounts::Tokens

Inherits:
Hash
  • Object
show all
Defined in:
lib/gsquire/accounts/tokens.rb

Constant Summary collapse

TOKENS_FILE =
'tokens.json'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Tokens

Returns a new instance of Tokens.

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :path (String)

    Path to GSquire database. Required and must exist.

  • :client (Client)

    Client instance. Required.



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/gsquire/accounts/tokens.rb', line 15

def initialize(opts = {})
  [:path, :client].each do |o|
    raise ArgumentError, "Option #{o.inspect} is required" unless opts.include?(o)
  end

  @options = opts
  @path = File.join options[:path], TOKENS_FILE
  @client = options[:client]
  
  super
  
  self.load!
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



9
10
11
# File 'lib/gsquire/accounts/tokens.rb', line 9

def client
  @client
end

#optionsObject (readonly)

Returns the value of attribute options.



9
10
11
# File 'lib/gsquire/accounts/tokens.rb', line 9

def options
  @options
end

#pathObject (readonly)

Returns the value of attribute path.



9
10
11
# File 'lib/gsquire/accounts/tokens.rb', line 9

def path
  @path
end

Instance Method Details

#[]=(name, token) ⇒ Object Also known as: store



65
66
67
68
69
70
71
# File 'lib/gsquire/accounts/tokens.rb', line 65

def []=(name, token)
  token.params[:name] = name if token.respond_to? :params
  r = super
  dirty!
  save
  r
end

#clean?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/gsquire/accounts/tokens.rb', line 54

def clean?
  !dirty?
end

#delete(name) ⇒ Object



74
75
76
77
78
79
# File 'lib/gsquire/accounts/tokens.rb', line 74

def delete(name)
  r = super
  dirty!
  save
  r
end

#dirty?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/gsquire/accounts/tokens.rb', line 50

def dirty?
  @dirty
end

#load!Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/gsquire/accounts/tokens.rb', line 39

def load!
  hash = begin
      from_json(File.read path)
    rescue JSON::ParserError, Errno::ENOENT
      {}
    end
  replace hash
  clean!
  self
end

#saveObject



29
30
31
32
33
34
35
36
37
# File 'lib/gsquire/accounts/tokens.rb', line 29

def save
  if dirty?
    File.open(path, 'w') do |f|
      f.write self.to_json
    end
    clean!
  end
  self
end

#to_jsonObject



58
59
60
61
62
63
# File 'lib/gsquire/accounts/tokens.rb', line 58

def to_json
  inject({}) do |hash, key_value|
    hash.store key_value[0], token_hash(key_value[1])
    hash
  end.to_json
end