mirror of https://github.com/rails/rails
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:
parent
a8871e6829
commit
da7a6da4e7
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue