Module: Card::Format::MethodDelegation

Included in:
Card::Format
Defined in:
lib/card/format/method_delegation.rb

Constant Summary collapse

RENDER_METHOD_RE =
/^
   (?<underscore>_)?  # leading underscore to skip permission check
   render
   (?:_(?<view>\w+))? # view name
   (?<bang>!)?        # trailing bang to skip optional check
$/x

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *opts, &proc) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/card/format/method_delegation.rb', line 16

def method_missing method, *opts, &proc
  if method =~ RENDER_METHOD_RE
    api_render Regexp.last_match, opts
  else
    pass_method_to_template_object(method, opts, proc) { yield }
  end
end

Instance Method Details

#api_render(match, opts) ⇒ Object



24
25
26
27
28
# File 'lib/card/format/method_delegation.rb', line 24

def api_render match, opts
  # view can be part of method name or first argument
  view = match[:view] || opts.shift
  render! view, render_args(match[:underscore], match[:bang], opts)
end

#pass_method_to_template_object(method, opts, proc) ⇒ Object



37
38
39
40
41
# File 'lib/card/format/method_delegation.rb', line 37

def pass_method_to_template_object method, opts, proc
  proc = proc { |*a| raw yield(*a) } if proc
  response = root.template.send method, *opts, &proc
  response.is_a?(String) ? root.template.raw(response) : response
end

#render_args(underscore, bang, opts) ⇒ Object



30
31
32
33
34
35
# File 'lib/card/format/method_delegation.rb', line 30

def render_args underscore, bang, opts
  args = opts[0] ? opts.shift.clone : {}   # opts are opts ;)
  args[:optional] = (opts.shift || args[:optional] || :show) unless bang
  args[:skip_perms] = true if underscore
  args
end

#respond_to_missing?(method, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/card/format/method_delegation.rb', line 12

def respond_to_missing? method, _include_private=false
  (method =~ RENDER_METHOD_RE) || template.respond_to?(method)
end