Module: HappyPlace::Controller

Extended by:
ActiveSupport::Concern
Defined in:
lib/happy_place/controller.rb

Instance Method Summary collapse

Instance Method Details

#auto_exec_function(class_and_function, args) ⇒ Object



50
51
52
# File 'lib/happy_place/controller.rb', line 50

def auto_exec_function(class_and_function, args)
  "<script type='application/javascript'>jQuery(document).ready(function($) {" + render_to_string(js: class_and_function + args) + "});</script>"
end

#build_args(partials, args) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/happy_place/controller.rb', line 40

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).join(", ") + "});"
  end
end

#build_class_and_function(js_class, function) ⇒ Object



34
35
36
37
38
# File 'lib/happy_place/controller.rb', line 34

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) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/happy_place/controller.rb', line 63

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) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/happy_place/controller.rb', line 54

def hash_to_js_args(args)
  js_args = []

  args.each_pair do |k, v|
    js_args << (k.to_s + ": " + "'#{v}'")
  end
  js_args
end

#js(js_class: nil, function: nil, partials: {}, args: {}) ⇒ Object

instance methods to go on every controller go here



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/happy_place/controller.rb', line 16

def js(js_class: nil, function: nil, partials: {}, args: {})
  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
    response_body = response.body
    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
  end
end