Class: Msf::OptTimedelta
- Defined in:
- lib/msf/core/opt_timedelta.rb
Constant Summary collapse
- TIMEDELTA_REGEX =
/\A([+-]?\d+(?:\.\d+)?(?:[smhd])?)+\z/i.freeze
- UNIT_IN_SECONDS =
{ 's' => 1, 'm' => 60, 'h' => 3_600, 'd' => 86_400 }.freeze
Instance Attribute Summary collapse
-
#allow_negative ⇒ Object
readonly
Returns the value of attribute allow_negative.
Attributes inherited from OptBase
#advanced, #aliases, #conditions, #default, #desc, #enums, #evasion, #fallbacks, #max_length, #name, #owner, #regex, #required
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(in_name, attrs = [], allow_negative: true, **kwargs) ⇒ OptTimedelta
constructor
A new instance of OptTimedelta.
- #normalize(value) ⇒ Object
- #type ⇒ Object
- #valid?(value, check_empty: true, datastore: nil) ⇒ Boolean
Methods inherited from OptBase
#advanced?, #display_value, #empty_required_value?, #evasion?, #invalid_value_length?, #required?, #type?, #validate_on_assignment?
Constructor Details
#initialize(in_name, attrs = [], allow_negative: true, **kwargs) ⇒ OptTimedelta
Returns a new instance of OptTimedelta.
18 19 20 21 |
# File 'lib/msf/core/opt_timedelta.rb', line 18 def initialize(in_name, attrs = [], allow_negative: true, **kwargs) super(in_name, attrs, **kwargs) @allow_negative = allow_negative end |
Instance Attribute Details
#allow_negative ⇒ Object (readonly)
Returns the value of attribute allow_negative.
16 17 18 |
# File 'lib/msf/core/opt_timedelta.rb', line 16 def allow_negative @allow_negative end |
Class Method Details
.parse(value) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/msf/core/opt_timedelta.rb', line 45 def self.parse(value) return 0 if value.nil? return value.to_f if value.is_a?(Numeric) trimmed_value = value.to_s.strip return 0 if trimmed_value.empty? return trimmed_value.to_f if trimmed_value.match?(/\A[+-]?\d+(?:\.\d+)?\z/) raise Msf::OptionValidateError.new([], message: 'Invalid timedelta format') unless trimmed_value.match?(TIMEDELTA_REGEX) total = 0 trimmed_value.scan(/([+-]?\d+(?:\.\d+)?)([smhd]?)/i) do |amount, unit| unit = 's' if unit.blank? multiplier = UNIT_IN_SECONDS[unit.downcase] total += amount.to_f * multiplier end total end |
Instance Method Details
#normalize(value) ⇒ Object
27 28 29 |
# File 'lib/msf/core/opt_timedelta.rb', line 27 def normalize(value) self.class.parse(value) end |
#type ⇒ Object
23 24 25 |
# File 'lib/msf/core/opt_timedelta.rb', line 23 def type 'timedelta' end |
#valid?(value, check_empty: true, datastore: nil) ⇒ Boolean
31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/msf/core/opt_timedelta.rb', line 31 def valid?(value, check_empty: true, datastore: nil) return false if check_empty && empty_required_value?(value) begin parsed_value = self.class.parse(value) rescue Msf::OptionValidateError return false end return false if !allow_negative && parsed_value.negative? super end |