make module for *_with macro

This commit is contained in:
Kanezoh 2021-06-25 09:15:43 +09:00
parent 2c5238c5f5
commit 33e94c110e
2 changed files with 47 additions and 40 deletions

View File

@ -4,8 +4,11 @@ require "./form/check_box"
require "./form/text" require "./form/text"
require "./form/hidden" require "./form/hidden"
require "./form/button" require "./form/button"
require "./utils/element_matcher"
class MechanizeCr::Form class MechanizeCr::Form
include MechanzeCr::ElementMatcher
getter fields : Array(FormContent::Field) getter fields : Array(FormContent::Field)
getter checkboxes : Array(FormContent::CheckBox) getter checkboxes : Array(FormContent::CheckBox)
getter radiobuttons : Array(FormContent::RadioButton) getter radiobuttons : Array(FormContent::RadioButton)
@ -43,46 +46,8 @@ class MechanizeCr::Form
# These methods are used for finding nodes that matches conditions. # These methods are used for finding nodes that matches conditions.
# ex.) field_with("email") finds <input name="email"> # ex.) field_with("email") finds <input name="email">
{% for singular, index in ["field", "radiobutton"] %} elements_with "field"
{% plural = "#{singular.id}s" %} elements_with "radiobutton"
def {{plural.id}}_with(criteria)
{{plural.id}}_with(criteria){}
end
def {{plural.id}}_with(criteria, &block)
value = Hash(String,String).new
if criteria.is_a?(String)
criteria = {"name" => criteria}
else
# TODO
# when args whose type isn't String is given
criteria = criteria.each_with_object(Hash(String,String).new) do |(k, v), h|
case k = k.to_s
when "id"
h["id"] = v
when "class"
h["class"] = v
else
h[k] = v
end
end
end
f = {{plural.id}}.select do |elm|
criteria.all? do |k,v|
v === elm.node.fetch(k,"x")
end
end
yield f
f
end
def {{singular.id}}_with(criteria)
f = {{plural.id}}_with(criteria)
# TODO: Write correct error message.
raise ElementNotFoundError.new(:{{singular.id}}, "") if f.empty?
f.first
end
{% end %}
private def parse private def parse
@node.css("input").not_nil!.each do |html_node| @node.css("input").not_nil!.each do |html_node|

View File

@ -0,0 +1,42 @@
module MechanzeCr::ElementMatcher
macro elements_with(singular)
{% plural = "#{singular.id}s" %}
def {{plural.id}}_with(criteria)
{{plural.id}}_with(criteria){}
end
def {{plural.id}}_with(criteria, &block)
value = Hash(String,String).new
if criteria.is_a?(String)
criteria = {"name" => criteria}
else
# now,
criteria = criteria.each_with_object(Hash(String,String).new) do |(k, v), h|
h[k] = v
#case k = k.to_s
#when "id"
# h["id"] = v
#when "class"
# h["class"] = v
#else
# h[k] = v
#end
end
end
f = {{plural.id}}.select do |elm|
criteria.all? do |k,v|
v === elm.node.fetch(k,"x")
end
end
yield f
f
end
def {{singular.id}}_with(criteria)
f = {{plural.id}}_with(criteria)
# TODO: Write correct error message.
raise ElementNotFoundError.new(:{{singular.id}}, "") if f.empty?
f.first
end
end
end