From d425f2a974b05c124131d446e1e70689d8123039 Mon Sep 17 00:00:00 2001 From: victor Date: Fri, 1 Nov 2024 16:38:03 +0100 Subject: [PATCH 1/2] Enhance hashcash_hidden_field_tag to accept custom HTML attributes and generate a unique ID --- lib/active_hashcash.rb | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/lib/active_hashcash.rb b/lib/active_hashcash.rb index 2a11d3a..afbad52 100644 --- a/lib/active_hashcash.rb +++ b/lib/active_hashcash.rb @@ -83,8 +83,16 @@ def hashcash_after_success # Call it inside the form that have to be protected and don't forget to initialize the JavaScript Hascash.setup(). # Unless you need something really special, you should not need to override this method. - def hashcash_hidden_field_tag(name = :hashcash) - options = {resource: hashcash_resource, bits: hashcash_bits, waiting_message: hashcash_waiting_message} - view_context.hidden_field_tag(name, "", "data-hashcash" => options.to_json) + def hashcash_hidden_field_tag(name = :hashcash, **html_attributes) + options = { + resource: hashcash_resource, + bits: hashcash_bits, + waiting_message: hashcash_waiting_message + } + html_attributes[:id] ||= "hashcash_#{SecureRandom.hex(4)}" + html_attributes["data-hashcash"] ||= options.to_json + html_attributes["data-controller"] ||= "hashcash" + + view_context.hidden_field_tag(name, "", **html_attributes) end end From e89c7ebbfbb2006d8475795773f721d8f019b012 Mon Sep 17 00:00:00 2001 From: victor Date: Thu, 14 Nov 2024 13:11:57 +0100 Subject: [PATCH 2/2] Update hashcash setup to select input elements with IDs starting with 'hashcash' --- lib/hashcash.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/hashcash.js b/lib/hashcash.js index 0006fa7..f2f7156 100644 --- a/lib/hashcash.js +++ b/lib/hashcash.js @@ -14,7 +14,7 @@ Hashcash = function(input) { Hashcash.setup = function() { if (document.readyState != "loading") { - var input = document.querySelector("input#hashcash") + var input = document.querySelector("input[id^=hashcash]") input && new Hashcash(input) } else document.addEventListener("DOMContentLoaded", Hashcash.setup )