Class: Rust::GoogleFormMapping

Inherits:
Object
  • Object
show all
Defined in:
lib/rust/forms/google_forms.rb

Overview

Class that allows to read CSVs exported from Google Forms.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash, **options) ⇒ GoogleFormMapping

Returns a new instance of GoogleFormMapping.

Raises:

  • (TypeError)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rust/forms/google_forms.rb', line 29

def initialize(hash, **options)
    raise TypeError, "Hash should be an hash" unless hash.is_a?(Hash)
    raise TypeError, "Mapping for question #{question} must have either all String keys or all Regexp keys." if !hash.keys.all? { |m| m.is_a?(Regexp) } && !hash.keys.all? { |m| m.is_a?(String) }
    raise "Unsupported options: #{options.keys - [:strip, :downcase]}" if (options.keys - [:strip, :downcase]).size > 0

    if hash.keys.all? { |m| m.is_a?(Regexp) }
        @type = :regexp
    else
        @type = :direct
    end

    @strip = options[:strip]
    @downcase = options[:downcase]

    if @type == :direct
        @hash = {}
        hash.each do |k, v|
            @hash[normalize(k)] = v
        end
    else
        @hash = hash
    end
end

Class Method Details

.load(filename, key_from = "from", key_to = "to", **options) ⇒ Object

Loads a mapping from a CSV file that can be used in the constructor of GoogleForm given the CSV filename and the keys for defining what should be transformed (key_from) in what (key_to). Returns a hash with the mapping from -> to.

Raises:

  • (TypeError)


15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rust/forms/google_forms.rb', line 15

def self.load(filename, key_from="from", key_to="to", **options)
    raise TypeError, "Expected string for filename" unless filename.is_a?(String)
    raise TypeError, "Expected string for key_from" unless key_from.is_a?(String)
    raise TypeError, "Expected string for key_to" unless key_to.is_a?(String)

    result = {}
    mapping = Rust::CSV.read(filename, headers: true)
    mapping.each do |r|
        result[r[key_from]] = r[key_to]
    end

    return GoogleFormMapping.new(result, **options)
end

Instance Method Details

#get(from) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rust/forms/google_forms.rb', line 53

def get(from)
    if @type == :regexp
        @hash.each do |k, v|
            if from.match(k)
                return v
            end
        end
        return from
    elsif @type == :direct
        return @hash[normalize(from)] || from
    end
end