Class: Handlebars::Helpers::CodeJavascript::AsJavascript
- Inherits:
-
BaseSafeStringHelper
- Object
- BaseHelper
- BaseSafeStringHelper
- Handlebars::Helpers::CodeJavascript::AsJavascript
- Defined in:
- lib/handlebars/helpers/code_javascript/as_javascript.rb
Overview
take ruby object and write it out as Javascript notation
Instance Method Summary collapse
- #handlebars_helper ⇒ Object
-
#hash_to_javascript(value) ⇒ Object
Convert ruby hash to javascript notation.
-
#parse(value, format) ⇒ String
Parse will take ruby object and write it out as Javascript notation.
- #remove_root_brace(javascript) ⇒ Object
Methods inherited from BaseSafeStringHelper
Methods inherited from BaseHelper
#parse_json, #struct_to_hash, #tokenizer, #wrapper
Instance Method Details
#handlebars_helper ⇒ Object
40 41 42 43 44 45 46 47 48 |
# File 'lib/handlebars/helpers/code_javascript/as_javascript.rb', line 40 def 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) ⇒ Object
Convert ruby hash to javascript notation
convert
{ "david": "cruwys" }
to
{ david: "cruwys" }
56 57 58 59 60 61 62 63 64 |
# 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) ⇒ String
Parse will take ruby object and write it out as Javascript notation
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# 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) ⇒ Object
66 67 68 |
# 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 |