Permalink
Browse files

Adding param to ActionController::Metal, param is a method that can h…

…andle with nested params hashes
  • Loading branch information...
1 parent 7735a41 commit f208b952ac570361256047efbc160beaa6579caa @guilleiguaran committed Mar 7, 2012
View
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##
+* Added ActionController::Metal#param method that can handle with nested params hashes.
+ For instance, param("user.id") is the same as params[:user].is_a?(Hash) && params[:user][:id].
+
+ *Guillermo Iguaran*
+
* Remove the leading \n added by textarea on assert_select. *Santiago Pastorino*
* Changed default value for `config.action_view.embed_authenticity_token_in_remote_forms`
@@ -148,6 +148,16 @@ def params=(val)
@_params = val
end
+ # Method that can handle with nested params hashes.
+ # For instance, param("user.id") is the same as
+ # params[:user].is_a?(Hash) && params[:user][:id]
+ def param(key)
+ key.to_s.split('.').inject(params) do |param, key|
+ return unless param
+ param[key]
+ end
+ end
+
# Basic implementations for content_type=, location=, and headers are
# provided to reduce the dependency on the RackDelegation module
# in Renderer and Redirector.
@@ -32,6 +32,14 @@ def test_nested_params
end
end
+ def test_param
+ with_test_route_set do
+ post "/", {"user" => {"username" => "gorbachev"}}
+ assert_equal "gorbachev", @controller.param("user.username")
+ assert_nil @controller.param("user.baz")
+ end
+ end
+
private
def with_test_route_set
with_routing do |set|
@@ -110,6 +110,8 @@ When this form is submitted, the value of +params[:client]+ will be <tt>{"name"
Note that the +params+ hash is actually an instance of +HashWithIndifferentAccess+ from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys.
+For convenience the +params+ hash also can be accessed using with the +param+ method. For instance, param("client.name") is the same as params[:client][:name].
+
h4. JSON/XML parameters
If you're writing a web service application, you might find yourself more comfortable on accepting parameters in JSON or XML format. Rails will automatically convert your parameters into +params+ hash, which you'll be able to access like you would normally do with form data.

0 comments on commit f208b95

Please sign in to comment.