Sha256: 2b6e66fefe5e28fe2ddb6dc911aa1e2b38b0c90c49fbd49b1962586629507398

Contents?: true

Size: 2 KB

Versions: 6

Compression:

Stored size: 2 KB

Contents

module GoogleVisualr

  module ParamHelpers

    def stringify_keys!(options)
      options.keys.each do |key|
        options[key.to_s] = options.delete(key)
      end
      options
    end

    def js_parameters(options)
      return "" if options.nil?

      attributes = options.collect { |(key, value)| "#{key}: #{typecast(value)}" }
      "{" + attributes.join(", ") + "}"
    end

    # If the column type is 'string'    , the value should be a string.
    # If the column type is 'number'    , the value should be a number.
    # If the column type is 'boolean'   , the value should be a boolean.
    # If the column type is 'date'      , the value should be a Date object.
    # If the column type is 'datetime'  , the value should be a DateTime or Time object.
    # If the column type is 'timeofday' , the value should be an array of three or four numbers: [hour, minute, second, optional milliseconds].
    # Returns an array of strings if given an array
    # Returns 'null' when value is nil.
    # Recursive typecasting when value is a hash.
    def typecast(value, type = nil)
      case
        when value.is_a?(String)
          return value.to_json
        when value.is_a?(Integer)   || value.is_a?(Float)
          return value
        when value.is_a?(TrueClass) || value.is_a?(FalseClass)
          return "#{value}"
        when value.is_a?(DateTime)  ||  value.is_a?(Time)
          if type == "time"
            return "new Date(0, 0, 0, #{value.hour}, #{value.min}, #{value.sec})"
          else
            return "new Date(#{value.year}, #{value.month-1}, #{value.day}, #{value.hour}, #{value.min}, #{value.sec})"
          end
        when value.is_a?(Date)
          return "new Date(#{value.year}, #{value.month-1}, #{value.day})"
        when value.nil?
          return "null"
        when value.is_a?(Array)
          return "[" + value.map{|v| typecast(v) }.join(',') + "]"
        when value.is_a?(Hash)
          return js_parameters(value)
        else
          return value
      end
    end

  end

end

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
google_visualr_rails5-2.5.2 lib/google_visualr/param_helpers.rb
google_visualr-2.5.1 lib/google_visualr/param_helpers.rb
google_visualr-2.5.0 lib/google_visualr/param_helpers.rb
google_visualr-2.4.0 lib/google_visualr/param_helpers.rb
google_visualr-2.3.0 lib/google_visualr/param_helpers.rb
google_visualr-2.2.0 lib/google_visualr/param_helpers.rb