Module: Cubscout::Scopes::ClassMethods

Defined in:
lib/cubscout/scopes.rb

Instance Method Summary collapse

Instance Method Details

#all(options = {}) ⇒ Cubscout::List

used with a collection endpoint, get all objects of a certain kind

Examples:

foos = Foo.all(tag: "bar")
foos.total_size # 335 with this filter
foos.each { |foo_element| puts "ID is #{foo_element.id}" }

Parameters:

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

    Optional query params described in Helspcout API documentation

Returns:

  • (Cubscout::List)

    Returns a List collection where items are instances of the class where the method is called.

Raises:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/cubscout/scopes.rb', line 34

def all(options = {})
  raise Error, "`#{self}.all` method is not available" unless path

  raw_first_or_requested_page = Cubscout.connection.get(path, page: options[:page] || 1, **options).body
  first_or_requested_page = List.new(raw_first_or_requested_page, path, self)

  if options[:page]
    first_or_requested_page
  else
    last_page_number = first_or_requested_page.number_of_pages

    raw_other_pages_items = (2..last_page_number).to_a.map do |page|
      Array(Cubscout.connection.get(path, page: page, **options).body.dig("_embedded", path))
    end

    raw_all_pages = {
      "_embedded" => { path => (Array(raw_first_or_requested_page.dig("_embedded", path)) + raw_other_pages_items).flatten },
      "page" => {
        "number" => first_or_requested_page.page,
        "size" => first_or_requested_page.total_size,
        "totalPages" => first_or_requested_page.number_of_pages,
        "totalElements" => first_or_requested_page.total_size
      }
    }
    List.new(raw_all_pages, path, self)
  end
end

#endpoint(path) ⇒ Object

DSL: necessary to provide the endpoint of the resources to query.

Examples:

class Conversation
  include Cubscout::Scopes
  endpoint "conversations"
end

Parameters:

  • path (String)

    path to the endpoint, without leading slash



18
19
20
# File 'lib/cubscout/scopes.rb', line 18

def endpoint(path)
  @path = path
end

#find(id, options = {}) ⇒ Object

used with an instance endpoint, get one instance of an Object

Parameters:

  • id (Integer)

    ID of the object to get

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

    Optional query params described in Helspcout API documentation

Returns:

  • (Object)

    Returns an instance of the class where the method is called. Example: Foo.find(123) # => returns an instance of Foo

Raises:



67
68
69
70
71
# File 'lib/cubscout/scopes.rb', line 67

def find(id, options = {})
  raise Error, "`#{self}.find` method is not available" unless path

  self.new(Cubscout.connection.get("#{path}/#{id}", options).body)
end

#pathObject

Read the path entered through the DSL



23
24
25
# File 'lib/cubscout/scopes.rb', line 23

def path
  @path
end