Class: Judges::Options

Inherits:
Object show all
Defined in:
lib/judges/options.rb

Overview

Options for Ruby scripts in the judges.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright © 2024 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(pairs = nil) ⇒ Options

Ctor.

Parameters:

  • pairs (Array<String>) (defaults to: nil)

    List of pairs, like [“token=af73cd3”, “max_speed=1”]



32
33
34
# File 'lib/judges/options.rb', line 32

def initialize(pairs = nil)
  @pairs = pairs
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args) ⇒ Object

Get option by name.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/judges/options.rb', line 57

def method_missing(*args)
  @hash ||= begin
    pp = @pairs || []
    pp = @pairs.map { |k, v| "#{k}=#{v}" } if pp.is_a?(Hash)
    pp = pp.split(',') if pp.is_a?(String)
    pp.compact!
    pp.reject!(&:empty?)
    pp.to_h do |pair|
      p = pair.split('=', 2)
      k = p[0].strip
      v = p[1]
      v = v.nil? ? 'true' : v.strip
      [k.to_sym, v.match?(/^[0-9]+$/) ? v.to_i : v]
    end
  end
  k = args[0].downcase
  @hash[k]
end

Instance Method Details

#+(other) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/judges/options.rb', line 36

def +(other)
  touch # this will trigger method_missing() method, which will create @hash
  h = @hash.dup
  other.touch # this will trigger method_missing() method, which will create @hash
  other.instance_variable_get(:@hash).each do |k, v|
    h[k] = v
  end
  Judges::Options.new(h.map { |k, v| "#{k}=#{v}" })
end

#respond_to?(_method, _include_private = false) ⇒ Boolean

rubocop:disable Style/OptionalBooleanParameter

Returns:

  • (Boolean)


77
78
79
80
# File 'lib/judges/options.rb', line 77

def respond_to?(_method, _include_private = false)
  # rubocop:enable Style/OptionalBooleanParameter
  true
end

#respond_to_missing?(_method, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


82
83
84
# File 'lib/judges/options.rb', line 82

def respond_to_missing?(_method, _include_private = false)
  true
end

#to_sObject

Convert them all to a string (printable in a log).



47
48
49
50
51
52
53
54
# File 'lib/judges/options.rb', line 47

def to_s
  touch # this will trigger method_missing() method, which will create @hash
  @hash.map do |k, v|
    v = v.to_s
    v = "#{v[0..3]}#{'*' * (v.length - 4)}" if v.length > 8
    "#{k} → \"#{v}\""
  end.join("\n")
end