Module: NormalizeDigits
- Defined in:
- lib/normalize_digits/version.rb,
lib/normalize_digits/matchers.rb,
lib/normalize_digits.rb
Defined Under Namespace
Modules: Matchers
Constant Summary collapse
- VERSION =
"0.1.1"- VALID_OPTIONS =
i[only except].freeze
- EN_DIGITS =
"0123456789"- AR_DIGITS =
"٠١٢٣٤٥٦٧٨٩"- HI_DIGITS =
"०१२३४५६७८९"- UR_DIGITS =
"۰۱۲۳۴۵۶۷۸۹"- AVAILABLE_LANGUAGES =
[AR_DIGITS, HI_DIGITS, UR_DIGITS].freeze
Class Method Summary collapse
- .convert(record_or_attribute, options = nil) ⇒ Object
- .convert_record(record, options = nil) ⇒ Object
- .convert_string(value) ⇒ Object
-
.narrow(attributes, options = {}) ⇒ Object
Necessary because Rails has removed the narrowing of attributes using :only and :except on Base#attributes.
- .validate_options(options) ⇒ Object
Class Method Details
.convert(record_or_attribute, options = nil) ⇒ Object
26 27 28 29 30 31 32 33 34 |
# File 'lib/normalize_digits.rb', line 26 def self.convert(record_or_attribute, = nil) if record_or_attribute.respond_to?(:attributes) convert_record(record_or_attribute, ) elsif record_or_attribute.is_a?(String) convert_string(record_or_attribute) else record_or_attribute end end |
.convert_record(record, options = nil) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/normalize_digits.rb', line 36 def self.convert_record(record, = nil) attributes = narrow(record.attributes, ) attributes.each do |attr, value| if value.is_a?(String) && !attr.include?("password") record[attr] = convert_string(value) end end record end |
.convert_string(value) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/normalize_digits.rb', line 48 def self.convert_string(value) AVAILABLE_LANGUAGES.each do |lang| begin value = value.try(:force_encoding, "UTF-8") rescue FrozenError value = value.dup.try(:force_encoding, "UTF-8") end value = value.try(:tr, lang, EN_DIGITS) end value end |
.narrow(attributes, options = {}) ⇒ Object
Necessary because Rails has removed the narrowing of attributes using :only and :except on Base#attributes
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/normalize_digits.rb', line 64 def self.narrow(attributes, = {}) return attributes if .blank? if [:except] except = [:except] except = Array(except).map(&:to_s) attributes.except(*except) elsif [:only] only = [:only] only = Array(only).map(&:to_s) attributes.slice(*only) else attributes end end |
.validate_options(options) ⇒ Object
82 83 84 85 86 |
# File 'lib/normalize_digits.rb', line 82 def self.() keys = .keys = (keys - VALID_OPTIONS) raise ArgumentError, "Options does not specify #{invalid_options.inspect}" unless .empty? end |