Skip to content

Commit 743d1fc

Browse files
authored
Merge pull request rails#49042 from Shopify/add-parameters-extract-method
Add `extract_value` method to `ActionController::Parameters`
2 parents 0d46f69 + da7a6da commit 743d1fc

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

actionpack/CHANGELOG.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
* Add `ActionController::Parameters#extract_value` method to allow extracting serialized values from params
2+
3+
```ruby
4+
params = ActionController::Parameters.new(id: "1_123", tags: "ruby,rails")
5+
params.extract_value(:id) # => ["1", "123"]
6+
params.extract_value(:tags, delimiter: ",") # => ["ruby", "rails"]
7+
```
8+
9+
*Nikita Vasilevsky*
10+
111
* Parse JSON `response.parsed_body` with `ActiveSupport::HashWithIndifferentAccess`
212

313
Integrate with Minitest's new `assert_pattern` by parsing the JSON contents

actionpack/lib/action_controller/metal/strong_parameters.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,15 @@ def deep_dup
926926
end
927927
end
928928

929+
# Returns parameter value for the given +key+ separated by +delimiter+.
930+
#
931+
# params = ActionController::Parameters.new(id: "1_123", tags: "ruby,rails")
932+
# params.extract_value(:id) # => ["1", "123"]
933+
# params.extract_value(:tags, delimiter: ",") # => ["ruby", "rails"]
934+
def extract_value(key, delimiter: "_")
935+
@parameters[key].split(delimiter)
936+
end
937+
929938
protected
930939
attr_reader :parameters
931940

actionpack/test/controller/parameters/accessors_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,4 +421,14 @@ class ParametersAccessorsTest < ActiveSupport::TestCase
421421
@params.dig(:person, :addresses)[0] = { city: "Boston", state: "Massachusetts" }
422422
assert_equal "Boston", @params.dig(:person, :addresses, 0, :city)
423423
end
424+
425+
test "#extract_value splits param by delimiter" do
426+
params = ActionController::Parameters.new(
427+
id: "1_123",
428+
tags: "ruby,rails,web"
429+
)
430+
431+
assert_equal(["1", "123"], params.extract_value(:id))
432+
assert_equal(["ruby", "rails", "web"], params.extract_value(:tags, delimiter: ","))
433+
end
424434
end

0 commit comments

Comments
 (0)