Class: K8::ActionInfo

Inherits:
Object
  • Object
show all
Defined in:
lib/keight.rb

Overview

ex:

info = ActionInfo.new('PUT', '/api/books/{id}')
p info.method                 #=> "PUT"
p info.urlpath(123)           #=> "/api/books/123"
p info.form_action_attr(123)  #=> "/api/books/123?_method=PUT"

Constant Summary collapse

SUBCLASSES =

:nodoc:

[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(method, urlpath_format) ⇒ ActionInfo

Returns a new instance of ActionInfo.



1034
1035
1036
1037
# File 'lib/keight.rb', line 1034

def initialize(method, urlpath_format)
  @method = method
  @urlpath_format = urlpath_format   # ex: '/books/%s/comments/%s'
end

Instance Attribute Details

#method(name = nil) ⇒ Object (readonly)

Returns the value of attribute method.



1039
1040
1041
# File 'lib/keight.rb', line 1039

def method
  @method
end

Class Method Details

.create(meth, urlpath_pattern) ⇒ Object



1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
# File 'lib/keight.rb', line 1059

def self.create(meth, urlpath_pattern)
  ## ex: '/books/{id}' -> '/books/%s'
  #; [!1nk0i] replaces urlpath parameters with '%s'.
  #; [!a7fqv] replaces '%' with'%%'.
  rexp = /(.*?)\{(\w*?)(?::[^{}]*(?:\{[^{}]*?\}[^{}]*?)*)?\}/
  urlpath_format = ''; n = 0
  urlpath_pattern.scan(rexp) do |text, pname|
    next if pname == 'ext'   # ignore '.html' or '.json'
    urlpath_format << text.gsub(/%/, '%%') << '%s'
    n += 1
  end
  rest = n > 0 ? Regexp.last_match.post_match : urlpath_pattern
  urlpath_format << rest.gsub(/%/, '%%')
  #; [!btt2g] returns ActionInfoN object when number of urlpath parameter <= 4.
  #; [!x5yx2] returns ActionInfo object when number of urlpath parameter > 4.
  return (SUBCLASSES[n] || ActionInfo).new(meth, urlpath_format)
end

Instance Method Details

#form_action_attr(*args) ⇒ Object



1049
1050
1051
1052
1053
1054
1055
1056
1057
# File 'lib/keight.rb', line 1049

def form_action_attr(*args)
  #; [!qyhkm] returns '/api/books/123' when method is POST.
  #; [!kogyx] returns '/api/books/123?_method=PUT' when method is not POST.
  if @method == 'POST'
    return urlpath(*args)
  else
    return "#{urlpath(*args)}?_method=#{@method}"
  end
end

#urlpath(*args) ⇒ Object



1045
1046
1047
# File 'lib/keight.rb', line 1045

def urlpath(*args)
  return @urlpath_format % args
end