Class: Togglehq::User

Inherits:
Object
  • Object
show all
Defined in:
lib/togglehq/user.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ User

Returns a new instance of User.



5
6
7
# File 'lib/togglehq/user.rb', line 5

def initialize(params = {})
  @identifier = params[:identifier]
end

Instance Attribute Details

#identifierObject

Returns the value of attribute identifier.



3
4
5
# File 'lib/togglehq/user.rb', line 3

def identifier
  @identifier
end

Class Method Details

.find_by_identifier(identifier) ⇒ Object

Finds an app user by the given identifier. If no record is found, returns nil.



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/togglehq/user.rb', line 10

def self.find_by_identifier(identifier)
  response = Togglehq::Request.new("/users/#{identifier}").get!
  if response.status == 404
    return nil
  elsif response.status == 200
    json = JSON.parse(response.body)
    user = Togglehq::User.new(:identifier => identifier)
    user.persisted!
    return user
  else
    raise "Unexpected error finding user"
  end
end

.find_by_identifier!(identifier) ⇒ Object

Like find_by_identifier, except that if no record is found, raises an RuntimeError.



25
26
27
28
29
# File 'lib/togglehq/user.rb', line 25

def self.find_by_identifier!(identifier)
  user = self.find_by_identifier(identifier)
  raise "Could not find user with identifier #{identifier}" if user.nil?
  return user
end

Instance Method Details

#persisted!Object



48
49
50
# File 'lib/togglehq/user.rb', line 48

def persisted!
  @persisted = true
end

#saveObject

Saves a new user



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/togglehq/user.rb', line 32

def save
  response = Togglehq::Request.new("/users", {"user" => {"identifier" => self.identifier}}).post!
  if response.status == 200
    self.persisted!
    json = JSON.parse(response.body)
    if json.has_key?("message") && json["message"] == "user already exists"
      # load this user's preferences
      user = Togglehq::User.find_by_identifier(self.identifier)
    end
    return true
  else
    raise "unexpected error saving user"
  end
end