Class: Crate::Raw

Inherits:
Object show all
Defined in:
lib/crate/raw.rb

Constant Summary collapse

REPLACE =
{
  "\xe2\x80\x9c" => '"',
  "\xe2\x80\x9d" => '"',
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw, **options) ⇒ Raw

Returns a new instance of Raw.



71
72
73
74
# File 'lib/crate/raw.rb', line 71

def initialize(raw, **options)
  @options = { logger: Logger.new(nil), severity: Logger::WARN, **options }
  @raw = symbolize(make_hash(raw))
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



13
14
15
# File 'lib/crate/raw.rb', line 13

def options
  @options
end

Instance Method Details

#gsub(raw) ⇒ Object



44
45
46
47
48
49
# File 'lib/crate/raw.rb', line 44

def gsub(raw)
  gsub_(raw).tap do |replaced|
    log_if_changed(raw, replaced)
    log_if_harmful(replaced)
  end
end

#gsub_(raw) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/crate/raw.rb', line 15

def gsub_(raw)
  raw.dup.tap do |raw_|
    REPLACE.each do |pattern, replacement|
      raw_.gsub!(pattern, replacement)
    end
  end
end

#log(&block) ⇒ Object



23
24
25
# File 'lib/crate/raw.rb', line 23

def log(&block)
  options[:logger].add(options[:severity], &block)
end

#log_if_changed(raw, replaced) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/crate/raw.rb', line 27

def log_if_changed(raw, replaced)
  return if raw == replaced
  log do
    "#{options[:fullname]}: Harmful characters are changed " \
      "from: #{raw.inspect} to: #{replaced.inspect}"
  end
end

#log_if_harmful(replaced) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/crate/raw.rb', line 35

def log_if_harmful(replaced)
  bytes = replaced.each_char.reject(&:ascii_only?).map(&:bytes)
  return if bytes.empty?
  log do
    "#{options[:fullname]}: Harmful characters are still remained: " \
      "#{bytes.inspect}"
  end
end

#make_hash(raw) ⇒ Object



60
61
62
63
64
65
66
67
68
69
# File 'lib/crate/raw.rb', line 60

def make_hash(raw)
  case raw
  when String
    JSON.parse(gsub(raw), symbolize_names: true)
  when Hash
    raw
  else
    raise
  end
end

#symbolize(object) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/crate/raw.rb', line 51

def symbolize(object)
  case object
  when Hash
    object.map { |key, value| [key.to_sym, symbolize(value)] }.to_h
  else
    object
  end
end

#to_hashObject



76
77
78
# File 'lib/crate/raw.rb', line 76

def to_hash
  @raw
end