Class: SmsTools::EncodingDetection

Inherits:
Object
  • Object
show all
Defined in:
lib/sms_tools/encoding_detection.rb

Constant Summary collapse

MAX_LENGTH_FOR_ENCODING =
{
  ascii: {
    normal:       160,
    concatenated: 153,
  },
  gsm: {
    normal:       160,
    concatenated: 153,
  },
  unicode: {
    normal:       70,
    concatenated: 67,
  },
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ EncodingDetection

Returns a new instance of EncodingDetection.



22
23
24
# File 'lib/sms_tools/encoding_detection.rb', line 22

def initialize(text)
  @text = text
end

Instance Attribute Details

#textObject (readonly)

Returns the value of attribute text.



20
21
22
# File 'lib/sms_tools/encoding_detection.rb', line 20

def text
  @text
end

Instance Method Details

#ascii?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/sms_tools/encoding_detection.rb', line 37

def ascii?
  encoding == :ascii
end

#concatenated?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/sms_tools/encoding_detection.rb', line 49

def concatenated?
  concatenated_parts > 1
end

#concatenated_partsObject



53
54
55
56
57
58
59
# File 'lib/sms_tools/encoding_detection.rb', line 53

def concatenated_parts
  if length <= MAX_LENGTH_FOR_ENCODING[encoding][:normal]
    1
  else
    (length.to_f / MAX_LENGTH_FOR_ENCODING[encoding][:concatenated]).ceil
  end
end

#encodingObject



26
27
28
29
30
31
32
33
34
35
# File 'lib/sms_tools/encoding_detection.rb', line 26

def encoding
  @encoding ||=
    if text.ascii_only? and SmsTools.use_ascii_encoding?
      :ascii
    elsif SmsTools.use_gsm_encoding? and GsmEncoding.valid?(text)
      :gsm
    else
      :unicode
    end
end

#gsm?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/sms_tools/encoding_detection.rb', line 41

def gsm?
  encoding == :gsm
end

#lengthObject

Returns the number of symbols which the given text will eat up in an SMS message, taking into account any double-space symbols in the GSM 03.38 encoding.



70
71
72
73
74
75
76
77
78
79
# File 'lib/sms_tools/encoding_detection.rb', line 70

def length
  if unicode?
    length = text.chars.sum { |char| UnicodeEncoding.character_count(char) }
  else
    length = text.length
    length += text.chars.count { |char| GsmEncoding.double_byte?(char) } if gsm?
  end

  length
end

#maximum_length_for(concatenated_parts) ⇒ Object



61
62
63
64
65
# File 'lib/sms_tools/encoding_detection.rb', line 61

def maximum_length_for(concatenated_parts)
  message_type = concatenated_parts > 1 ? :concatenated : :normal

  concatenated_parts * MAX_LENGTH_FOR_ENCODING[encoding][message_type]
end

#unicode?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/sms_tools/encoding_detection.rb', line 45

def unicode?
  encoding == :unicode
end