Class: SecId::CUSIP

Inherits:
Base
  • Object
show all
Defined in:
lib/sec_id/cusip.rb

Overview

Constant Summary collapse

ID_REGEX =
/\A
  (?<identifier>
    (?<cusip6>[A-Z0-9]{5}[A-Z0-9*@#])
    (?<issue>[A-Z0-9*@#]{2}))
  (?<check_digit>\d)?
\z/x.freeze
VALID_COUNTRY_CODES_FOR_CONVERSION_TO_ISIN =
%w[US CA].freeze

Constants inherited from Base

Base::CHAR_TO_DIGIT, Base::CHAR_TO_DIGITS

Instance Attribute Summary collapse

Attributes inherited from Base

#check_digit, #identifier

Instance Method Summary collapse

Methods inherited from Base

check_digit, restore!, #to_s, valid?, valid_format?

Constructor Details

#initialize(cusip) ⇒ CUSIP

Returns a new instance of CUSIP.



17
18
19
20
21
22
23
24
25
# File 'lib/sec_id/cusip.rb', line 17

def initialize(cusip)
  @cusip = cusip.to_s.strip.upcase
  cusip_parts = @cusip.match(ID_REGEX) || {}

  @identifier = cusip_parts[:identifier]
  @cusip6 = cusip_parts[:cusip6]
  @issue = cusip_parts[:issue]
  @check_digit = cusip_parts[:check_digit].to_i if cusip_parts[:check_digit]
end

Instance Attribute Details

#cusipObject (readonly)

Returns the value of attribute cusip.



15
16
17
# File 'lib/sec_id/cusip.rb', line 15

def cusip
  @cusip
end

#cusip6Object (readonly)

Returns the value of attribute cusip6.



15
16
17
# File 'lib/sec_id/cusip.rb', line 15

def cusip6
  @cusip6
end

#issueObject (readonly)

Returns the value of attribute issue.



15
16
17
# File 'lib/sec_id/cusip.rb', line 15

def issue
  @issue
end

Instance Method Details

#calculate_check_digitObject

Raises:



42
43
44
45
46
# File 'lib/sec_id/cusip.rb', line 42

def calculate_check_digit
  return mod_10(modified_luhn_sum) if valid_format?

  raise InvalidFormatError, "CUSIP '#{cusip}' is invalid and check-digit cannot be calculated!"
end

#restore!Object



37
38
39
40
# File 'lib/sec_id/cusip.rb', line 37

def restore!
  @check_digit = calculate_check_digit
  @cusip = to_s
end

#valid?Boolean

Returns:

  • (Boolean)


27
28
29
30
31
# File 'lib/sec_id/cusip.rb', line 27

def valid?
  return false unless valid_format?

  check_digit == calculate_check_digit
end

#valid_format?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/sec_id/cusip.rb', line 33

def valid_format?
  identifier ? true : false
end