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.



995
996
997
998
# File 'lib/keight.rb', line 995

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

Instance Attribute Details

#methObject (readonly)

Returns the value of attribute meth.



1000
1001
1002
# File 'lib/keight.rb', line 1000

def meth
  @meth
end

Class Method Details

.create(meth, urlpath_pattern) ⇒ Object



1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'lib/keight.rb', line 1021

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



1011
1012
1013
1014
1015
1016
1017
1018
1019
# File 'lib/keight.rb', line 1011

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 @meth == 'POST'
    return path(*args)
  else
    return "#{path(*args)}?_method=#{@meth}"
  end
end

#method(name = nil) ⇒ Object

(experimental; use #meth instead)



1003
1004
1005
# File 'lib/keight.rb', line 1003

def method(name=nil)    # :nodoc:
  return name ? super : @meth
end

#path(*args) ⇒ Object



1007
1008
1009
# File 'lib/keight.rb', line 1007

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