Add `extract_value` method to `ActionController::Parameters`

This commit adds `extract_value` method to `ActionController::Parameters`
as a primary way to extract composite `id` values serialized from
`ActiveRecord::Base#to_param` called on a model with a composite primary key.
This commit is contained in:
Nikita Vasilevsky 2023-08-25 22:15:35 +00:00
parent a8871e6829
commit da7a6da4e7
No known key found for this signature in database
GPG Key ID: 0FF5725CD31059E4
3 changed files with 29 additions and 0 deletions

View File

@ -1,3 +1,13 @@
* Add `ActionController::Parameters#extract_value` method to allow extracting serialized values from params
```ruby
params = ActionController::Parameters.new(id: "1_123", tags: "ruby,rails")
params.extract_value(:id) # => ["1", "123"]
params.extract_value(:tags, delimiter: ",") # => ["ruby", "rails"]
```
*Nikita Vasilevsky*
* Parse JSON `response.parsed_body` with `ActiveSupport::HashWithIndifferentAccess`
Integrate with Minitest's new `assert_pattern` by parsing the JSON contents

View File

@ -926,6 +926,15 @@ module ActionController
end
end
# Returns parameter value for the given +key+ separated by +delimiter+.
#
# params = ActionController::Parameters.new(id: "1_123", tags: "ruby,rails")
# params.extract_value(:id) # => ["1", "123"]
# params.extract_value(:tags, delimiter: ",") # => ["ruby", "rails"]
def extract_value(key, delimiter: "_")
@parameters[key].split(delimiter)
end
protected
attr_reader :parameters

View File

@ -421,4 +421,14 @@ class ParametersAccessorsTest < ActiveSupport::TestCase
@params.dig(:person, :addresses)[0] = { city: "Boston", state: "Massachusetts" }
assert_equal "Boston", @params.dig(:person, :addresses, 0, :city)
end
test "#extract_value splits param by delimiter" do
params = ActionController::Parameters.new(
id: "1_123",
tags: "ruby,rails,web"
)
assert_equal(["1", "123"], params.extract_value(:id))
assert_equal(["ruby", "rails", "web"], params.extract_value(:tags, delimiter: ","))
end
end