Module: JcheckRails::Encoder

Extended by:
ActionView::Helpers::JavaScriptHelper
Defined in:
lib/jcheck_rails/encoder.rb

Class Method Summary collapse

Class Method Details

.convert_array(array) ⇒ Object



33
34
35
36
# File 'lib/jcheck_rails/encoder.rb', line 33

def convert_array(array)
  data = array.map { |x| convert_to_javascript(x) }
  "[#{data.join(', ')}]"
end

.convert_hash(hash) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/jcheck_rails/encoder.rb', line 38

def convert_hash(hash)
  hash_pairs = []

  hash.each do |k, v|
    hash_pairs << "#{convert_to_javascript(k)}: #{convert_to_javascript(v)}"
  end

  "{#{hash_pairs.join(", ")}}"
end

.convert_to_javascript(object) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/jcheck_rails/encoder.rb', line 8

def convert_to_javascript(object)
  return "true" if object == {}

  case object
    when TrueClass
      "true"
    when FalseClass
      "false"
    when NilClass
      "null"
    when Fixnum, Float
      object.to_s
    when Symbol, String
      "'#{escape_javascript object.to_s}'"
    when Regexp
      "/#{object.source}/#{regex_options_string(object.options)}"
    when Array
      convert_array(object)
    when Hash
      convert_hash(object)
    else
      raise ArgumentError.new("can't parse object type #{object.class}")
  end
end

.regex_options_string(options) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/jcheck_rails/encoder.rb', line 48

def regex_options_string(options)
  letters = [[1, "i"], [2, "x"], [4, "m"]]

  letters.inject("") do |acc, (v, l)|
    acc << l if (options & v) > 0
    acc
  end
end