Class: Cage::Console

Inherits:
Object
  • Object
show all
Defined in:
lib/cage/console.rb

Constant Summary collapse

CONNECTION_VARIABLES =
[:scheme, :domain, :prefix, :port, :headers]
HTTP_METHOD_REGEX =
/^(?:get|post|put|delete|head|options|patch)$/i

Instance Method Summary collapse

Constructor Details

#initialize(config_file_name = nil) ⇒ Console

Returns a new instance of Console.



8
9
10
11
12
13
# File 'lib/cage/console.rb', line 8

def initialize config_file_name = nil
  configure_pry
  read_config_file File.expand_path config_file_name if config_file_name
  default_to_rubygems
  reinitialize_connection
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object

TODO: Use same logic in both method_missing and respond_to?



26
27
28
29
30
31
32
33
34
35
# File 'lib/cage/console.rb', line 26

def method_missing sym, *args, &block
  case  sym
  when HTTP_METHOD_REGEX
    http sym, *args, &block
  when /^(?:basic|token)_auth/
    connection.send sym, *args, &block
  else
    super
  end
end

Instance Method Details

#add_middleware(&block) ⇒ Object



45
46
47
48
# File 'lib/cage/console.rb', line 45

def add_middleware &block
  @middleware_builder = block
  reinitialize_connection
end

#http(method, *args, &block) ⇒ Object



50
51
52
53
# File 'lib/cage/console.rb', line 50

def http method, *args, &block
  @last_response = Cage::Response.new connection.send method.downcase,
    *args, &block
end

#reinitialize_connectionObject



15
16
17
18
19
20
21
22
23
# File 'lib/cage/console.rb', line 15

def reinitialize_connection
  @connection = Faraday.new "#{@scheme}://#{@domain}#{":#{@port}" if @port}/#{@prefix}",
    :headers => @headers do |conn|
      conn.use FaradayMiddleware::ParseXml,  :content_type => /\bxml$/
      conn.use FaradayMiddleware::ParseJson, :content_type => /\bjson$/
      conn.adapter Faraday.default_adapter
      @middleware_builder.call conn unless @middleware_builder.nil?
    end
end

#respond_to?(method) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
# File 'lib/cage/console.rb', line 37

def respond_to? method
  if method =~ HTTP_METHOD_REGEX
    true
  else
    super
  end
end

#set(convar, value) ⇒ Object

Raises:

  • (ArgumentError)


55
56
57
58
59
60
61
# File 'lib/cage/console.rb', line 55

def set convar, value
  raise ArgumentError, "#{convar} isn't a connection variable" unless
    CONNECTION_VARIABLES.include? convar
  instance_variable_set :"@#{convar}", value
  reinitialize_connection
  value
end