Class: Wikidotrb::Module::UserCollection

Inherits:
Array
  • Object
show all
Defined in:
lib/wikidotrb/module/user.rb

Overview

Class representing a collection of users

Class Method Summary collapse

Class Method Details

.from_names(client, names, raise_when_not_found = false) ⇒ UserCollection

Get a list of user objects from a list of usernames

Parameters:

  • client (Client)

    The client

  • names (Array<String>)

    List of usernames

  • raise_when_not_found (Boolean) (defaults to: false)

    Whether to raise an exception when a user is not found

Returns:



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/wikidotrb/module/user.rb', line 17

def self.from_names(client, names, raise_when_not_found = false)
  urls = names.map { |name| "https://www.wikidot.com/user:info/#{Wikidotrb::Util::StringUtil.to_unix(name)}" }

  responses = Wikidotrb::Util::RequestUtil.request(client: client, method: "GET", urls: urls)

  users = []

  responses.each do |response|
    raise response if response.is_a?(Exception)

    html = Nokogiri::HTML(response.body.to_s)

    # Check existence
    if html.at_css("div.error-block")
      raise Wikidotrb::Common::Exceptions::NotFoundException, "User not found: #{response.uri}" if raise_when_not_found

      next
    end

    # Get ID
    user_id = html.at_css("a.btn.btn-default.btn-xs")["href"].split("/").last.to_i

    # Get name
    name = html.at_css("h1.profile-title").text.strip

    # Get avatar_url
    avatar_url = "https://www.wikidot.com/avatar.php?userid=#{user_id}"

    users << User.new(
      client: client,
      id: user_id,
      name: name,
      unix_name: Wikidotrb::Util::StringUtil.to_unix(name),
      avatar_url: avatar_url
    )
  end

  new(users)
end