Class: Castle::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/castle/client.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context, do_not_track = false) ⇒ Client

Returns a new instance of Client.



18
19
20
21
22
# File 'lib/castle/client.rb', line 18

def initialize(context, do_not_track = false)
  @do_not_track = do_not_track
  @context = context
  @api = API.new
end

Instance Attribute Details

#apiObject

Returns the value of attribute api.



16
17
18
# File 'lib/castle/client.rb', line 16

def api
  @api
end

Class Method Details

.from_request(request, options = {}) ⇒ Object



6
7
8
# File 'lib/castle/client.rb', line 6

def from_request(request, options = {})
  new(to_context(request, options), options[:do_not_track])
end

.to_context(request, options = {}) ⇒ Object



10
11
12
13
# File 'lib/castle/client.rb', line 10

def to_context(request, options = {})
  default_context = Castle::DefaultContext.new(request, options[:cookies]).call
  Castle::ContextMerger.new(default_context).call(options[:context] || {})
end

Instance Method Details

#authenticate(options = {}) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/castle/client.rb', line 24

def authenticate(options = {})
  options = Castle::Utils.deep_symbolize_keys(options || {})

  if tracked?
    command = Castle::Commands::Authenticate.new(@context).build(options)
    begin
      @api.request(command).merge(failover: false, failover_reason: nil)
    rescue Castle::RequestError, Castle::InternalServerError => error
      failover_response_or_raise(FailoverAuthResponse.new(options[:user_id], reason: error.to_s), error)
    end
  else
    FailoverAuthResponse.new(options[:user_id], strategy: :allow, reason: 'Castle set to do not track.').generate
  end
end

#disable_trackingObject



57
58
59
# File 'lib/castle/client.rb', line 57

def disable_tracking
  @do_not_track = true
end

#enable_trackingObject



61
62
63
# File 'lib/castle/client.rb', line 61

def enable_tracking
  @do_not_track = false
end

#identify(options = {}) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/castle/client.rb', line 39

def identify(options = {})
  options = Castle::Utils.deep_symbolize_keys(options || {})

  return unless tracked?

  command = Castle::Commands::Identify.new(@context).build(options)
  @api.request(command)
end

#track(options = {}) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/castle/client.rb', line 48

def track(options = {})
  options = Castle::Utils.deep_symbolize_keys(options || {})

  return unless tracked?

  command = Castle::Commands::Track.new(@context).build(options)
  @api.request(command)
end

#tracked?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/castle/client.rb', line 65

def tracked?
  !@do_not_track
end