Module: HelpfulUtils::CoreExt::String::JSON

Included in:
String
Defined in:
lib/helpful_utils/core_ext/string.rb

Instance Method Summary collapse

Instance Method Details

#json?Boolean

Проверка,является ли строка JSON’ом

Returns:

  • (Boolean)


31
32
33
34
35
# File 'lib/helpful_utils/core_ext/string.rb', line 31

def json?
  return true if !self.blank? && ActiveSupport::JSON.decode(self).is_a?(Hash)
rescue ActiveSupport::JSON::ParseError
  false
end

#to_json_with_russian_support(options = nil) ⇒ Object

Если вызывать у строки с русским текстом стандартный метод to_json, а потом попробовать отобразить ее то получится что то невразумительное.Данный метод исправляет проблему. Пример “тут русский текст”.to_json(:russian=>true) по умолчанию russian == false



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/helpful_utils/core_ext/string.rb', line 10

def to_json_with_russian_support(options = nil) #:nodoc:
  result = nil
  unless  options.blank?
    if options[:russian]== true
      json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s|
        ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s]
      }
      json.force_encoding('ascii-8bit') if respond_to?(:force_encoding)
      result = json + '"'
    end
  end
  if result.blank?
    result = to_json_without_russian_support options
  end
  result
end