From 2c5238c5f5064234091a1c2cc12523f56368b865 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Sat, 19 Jun 2021 07:55:11 +0900 Subject: [PATCH] WIP: field_with methods used id, search --- spec/form/field_spec.cr | 3 +++ src/mechanize/form.cr | 21 ++++++++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/spec/form/field_spec.cr b/spec/form/field_spec.cr index 37a13f6..caa35c5 100644 --- a/spec/form/field_spec.cr +++ b/spec/form/field_spec.cr @@ -42,6 +42,9 @@ describe "Form Fields" do it "can be found by field_with method" do name_field = form.field_with("name") name_field.name.should eq "name" + + email_field = form.field_with({"id" => "emailID"}) + email_field.name.should eq "email" end it "can be found by fields_with method" do diff --git a/src/mechanize/form.cr b/src/mechanize/form.cr index 0663d4d..d441854 100644 --- a/src/mechanize/form.cr +++ b/src/mechanize/form.cr @@ -51,15 +51,25 @@ class MechanizeCr::Form def {{plural.id}}_with(criteria, &block) value = Hash(String,String).new - if String === criteria - value = {"name" => criteria} + 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| - value.all? do |k,v| - v === elm.name + criteria.all? do |k,v| + v === elm.node.fetch(k,"x") end end yield f @@ -68,7 +78,8 @@ class MechanizeCr::Form def {{singular.id}}_with(criteria) f = {{plural.id}}_with(criteria) - raise ElementNotFoundError.new(:{{singular.id}}, criteria) if f.empty? + # TODO: Write correct error message. + raise ElementNotFoundError.new(:{{singular.id}}, "") if f.empty? f.first end {% end %}