module HappyPlace::Controller

Public Instance Methods

auto_exec_function(class_and_function, args, container=nil) click to toggle source
# File lib/happy_place/controller.rb, line 55
def auto_exec_function(class_and_function, args, container=nil)
  script_string = "<script type='application/javascript'>(function(){" + render_to_string(js: class_and_function + args) + "})();</script>"
  if container.present?
    script_string = container[:open] + script_string + container[:close]
  end
  script_string
end
build_args(partials, args) click to toggle source
# File lib/happy_place/controller.rb, line 45
def build_args(partials, args)
  if partials.present?
    built_args = "({" +
      (build_partials_string(partials) + hash_to_js_args(args)).join(", ") +
      "});"
  else
    built_args = "(" + hash_to_js_args(args) + ");"
  end
end
build_class_and_function(js_class, function) click to toggle source
# File lib/happy_place/controller.rb, line 39
def build_class_and_function(js_class, function)
  js_class ||= self.class.name.gsub("::", ".")
  function ||= action_name
  [js_class, function].join(".")
end
build_partials_string(partials) click to toggle source
# File lib/happy_place/controller.rb, line 73
def build_partials_string(partials)
  partials_strings = []
  partials.each_pair do |k, v|
    partials_strings << (k.to_s + ": " + "'#{(render_to_string partial: v).gsub("\n", "")}'")
  end
  partials_strings
end
hash_to_js_args(args) click to toggle source
# File lib/happy_place/controller.rb, line 63
def hash_to_js_args(args)
  # js_args = []

  # args.each_pair do |k, v|
  #   js_args << (k.to_s + ": " + "'#{v}'")
  # end
  # js_args
  args.to_json
end
js(js_class: nil, function: nil, partials: {}, args: {}, container: {}, rendered: false) click to toggle source

instance methods to go on every controller go here

# File lib/happy_place/controller.rb, line 16
def js(js_class: nil, function: nil, partials: {}, args: {}, container: {}, rendered: false)
  class_and_function = build_class_and_function(js_class, function)
  built_args = build_args(partials, args)
  case request.format.to_sym
  when :js
    render js: class_and_function + built_args
  when :html
    render unless rendered

    response_body = response.body
    if response_body.present?
      before_body_end_index = response_body.rindex('</body>')

      before_body = response_body[0, before_body_end_index].html_safe
      after_body = response_body[before_body_end_index..-1].html_safe

      response.body = before_body + auto_exec_function(class_and_function, built_args).html_safe + after_body
    else
      response.body = auto_exec_function(class_and_function, built_args.gsub("\n", ""), container).html_safe
    end
  end
end