Sha256: a6d3fbab93209ecb086a3a00d4820528417b3ab8fb9525ecdf0a7b2048b01151

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

module Gendered
  class Guesser

    attr_accessor :names, :country_id

    def initialize(values, country_id = nil)
      raise ArgumentError, "cannot be empty" if Array(values).empty?

      @names = Array(values)
      @country_id = country_id
    end

    def guess!
      response = HTTP.get(url)
      case response.code
      when 200

        guesses = JSON.parse(response.body)

        names.collect do |name|
          name = Name.new(name) if name.is_a?(String)

          guess = guesses.find { |g| g["name"] == name.value }

          if guess["gender"]
            name.gender = guess["gender"].to_sym
            name.probability = guess["probability"]
            name.sample_size = guess["count"]
          end

          name
        end
      end
    end

    def url
      url = "http://api.genderize.io/?"
      url += "country_id=#{country_id}&" if country_id

      name_queries = names.collect.with_index do |name, index|
        "name[#{index}]=#{CGI.escape(name.to_s)}"
      end
      url + name_queries.join("&")
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gendered-0.0.5 lib/gendered/guesser.rb