class Handlebars::Helpers::CodeJavascript::AsJavascript
take ruby object and write it out as Javascript notation
Public Instance Methods
handlebars_helper()
click to toggle source
# File lib/handlebars/helpers/code_javascript/as_javascript.rb, line 40 def handlebars_helper proc do |_context, value, format| # Handle optional: format format = nil if format.is_a?(V8::Object) format = format.to_sym if format.is_a?(String) wrapper(parse(value, format)) end end
hash_to_javascript(value)
click to toggle source
Convert ruby hash to javascript notation
convert
{ "david": "cruwys" }
to
{ david: "cruwys" }
# File lib/handlebars/helpers/code_javascript/as_javascript.rb, line 56 def hash_to_javascript(value) javascript = JSON.pretty_generate(value) rex = /"(?<name>\w*)":/ javascript.gsub(rex) do |_| "#{$LAST_MATCH_INFO['name']}:" end end
parse(value, format)
click to toggle source
Parse will take ruby object and write it out as Javascript notation
@example
puts AsJavascript.new.parse({david: "was here", why: ['reason1', 'reason2', 'reason3']}) { david: "was here", why: ['reason1', 'reason2', 'reason3'] }
@param [Object] value - object to be converted to Javascript notation string @return [String] value as Javascript string
# File lib/handlebars/helpers/code_javascript/as_javascript.rb, line 24 def parse(value, format) return '' if value.nil? format = :include_root_brace if format.nil? javascript = case value when Hash hash_to_javascript(value) when OpenStruct, V8::Object, V8::Array hash_to_javascript(parse_json(value)) end javascript = remove_root_brace(javascript) if format == :exclude_root javascript end
remove_root_brace(javascript)
click to toggle source
# File lib/handlebars/helpers/code_javascript/as_javascript.rb, line 66 def remove_root_brace(javascript) javascript.sub('{', '').tap { |s| s.slice!(s.rindex('}')) }.strip end