Cannot access params map using Groovy - grails

I want little help which I suspect is due to my lack of understanding for Groovy syntax. So, here's the thing:
On the GSP page I want to set a field's value from the params map which is
["id":"107901", "Field_10.value":"2", "Field_10":["value":"2"],"Field_11.value":"", "Field_11":["value":""],action:'abc']
On the gsp page, I want to find the value against the key Field_{some-id}.value
So I am calling a tag like, g.testTag(id:field.id) with its implementation as
def testTag = { attrs,body->
println "params are ${params}"
def result = ""
def keyRequired = "Field_${attrs.id}.value"
println "keyRequired >>>>> ${keyRequired.toString()}"
params.each { key,value->
println "key is ${key}"
println "Value is ${value}"
if (key.equals(keyRequired.toString())) {
result = params.value
}
}
println "Final result is >>>>>> ${result}"
}
The value passed in id is 10 and with my params printed as above, I was expecting a value
of 2 which is corresponding to the key in the params to show up. But apparently I see the
result as null..
What am I doing wrong ? Can anyone help please...
Thanks

Not result = params.value, but result = value.

You have to change the line:
result = params.value
to:
result = value
At the each loop, you're basically saying that inside the params iteration, you're naming every key "key" and every value "value". So, params.value will actually look for the key value inside your params map, which is null.
Funny that you do that right with key but not with value. Probably just got distracted.

it is likely what you want to do, the groovy way (no need to loop over the keys of the map) to access "Field_10.value":"2"
result=params["Field_${attrs.id}.value"]
Alternatively, this also works because you have "Field_10":["value":"2"] in your map
result=params["Field_${attrs.id}"].value

Related

parsing JSON request

The following #request = JSON.parse(request.body.read) is generating:
[
{
"application_id"=>"216",
"description"=>"Please double check date and time",
"release_date"=>"2018-12-01",
"auth"=>"someBigData"
}
]
However a blank is returned if invoking
Rails.logger.info #request['application_id']
and
if #request['auth'] == 'someBigData'
is generating a
TypeError (no implicit conversion of String into Integer):` in `app/controllers/base_controller.rb:55:in '[]'
What is wrong syntactically?
You're getting an array of hashes back, which is why #request['application_id'] returns a blank for you.
You'll need to do #request.first['application_id'] or #request[0]['application_id'] to index into your array.
As it's been already stated, you get this error cause #request is an array of hashes rather than a hash itself. To access "application_id" key of the first element you can also use dig method:
#request.dig(0, "application_id")
this way there is not going to be an exception in case #request is empty.

Why map.collectEntries() not working for this data [[Name:sub, Value:23234]] - Groovy

Why this works:
def m = [[1,11], [2,22], [3,33]]
println(m.collectEntries())
output: [1:11, 2:22, 3:33]
But this doesn't work:
def m = [[Name:sub, Value:23234], [Name:zoneinfo, Value:Europe/London]]
println(m.collectEntries())
output:
groovy.lang.MissingPropertyException: No such property: sub for class
I want to process that map so that I get a list of key value pairs like this:
["Name:sub" :"Value:23234", "Name:zoneinfo": "Value:Europe/London"]
where Name:sub is the key and Value:23234 is the value.
Reference https://stackoverflow.com/a/34899177/9992516
In the second example sub and zoneinfo are being read as variable names, not strings, and you need to quote them.
def m = [[Name:'sub', Value:23234], [Name:'zoneinfo', Value:'Europe/London']]
println m.collectEntries{ ["Name:${it.Name}", "Value:${it.Value}"] }
It cannot find sub field in your class, probably you want to have a string "sub"?
Basically, map entry can be declared in two ways:
Name: 'sub'
and
'Name': 'sub'
For the key it is assumed that is is a String, even if it is not wrapped by quotes.
But for the value it is mandatory to wrap in quotes. Otherwise, it is treated as a variable (or field)
Given your desired results:
["Name:sub" :"Value:23234", "Name:zoneinfo": "Value:Europe/London"]
What you actually need to do is quote the entire item in each pair:
def m = [["Name:sub", "Value:23234"], ["Name:zoneinfo", "Value:Europe/London"]]

Array.size() returned wrong values (Grails)

I'm developing an app using Grails. I want to get length of array.
I got a wrong value. Here is my code,
def Medias = params.medias
println params.medias // I got [37, 40]
println params.medias.size() // I got 7 but it should be 2
What I did wrong ?
Thanks for help.
What is params.medias (where is it being set)?
If Grials is treating it as a string, then using size() will return the length of the string, rather than an array.
Does:
println params.medias.length
also return 7?
You can check what Grails thinks an object is by using the assert keyword.
If it is indeed a string, you can try the following code to convert it into an array:
def mediasArray = Eval.me(params.medias)
println mediasArray.size()
The downside of this is that Eval presents the possibility of unwanted code execution if the params.medias is provided by an end user, or can be maliciously modified outside of your compiled code.
A good snippet on the "evil (or lack thereof) of eval" is here if you're interested (not mine):
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
I think 7 is result of length of the string : "[37,40]"
Seems your media variable is an array not a collection
Try : params.medias.length
Thanks to everyone. I've found my mistake
First of all, I sent an array from client and my params.medias returned null,so I converted it to string but it is a wrong way.
Finally, I sent and array from client as array and in the grails, I got a params by
params."medias[]"
List medias = params.list('medias')
Documentation: http://grails.github.io/grails-doc/latest/guide/single.html#typeConverters

Ruby, accessing a nested value in a hash

I have the following hash. Using ruby, I want to get the value of "runs". I can't figure out how to do it. If I do my_hash['entries'], I can dig down that far. If I take that value and dig down lower, I get this error:
no implicit conversion of String into Integer:
{"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588, ...
Assuming that you want to lookup values by id, Array#detect comes to the rescue:
h = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]}]}
# ⇓⇓⇓⇓⇓⇓⇓ lookup element with id = 7
h['entries'].detect { |e| e['id'] == 7 }['runs']
.detect { |e| e['id'] == 2588 }
#⇒ { "id" => 2588 }
As you have an array inside the entries so you can access it using an index like this:
my_hash["entries"][0]["runs"]
You need to follow the same for accessing values inside the runs as it is also an array.
Hope this helps.
I'm not sure about your hash, as it's incomplete. So , guessing you have multiple run values like:
hash = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]},
{"id"=>"8", "runs"=>[{"id"=>2589}]},
{"id"=>"9", "runs"=>[{"id"=>2590}]}]}
Then, you can do
hash["entries"].map{|entry| entry["runs"]}
OUTPUT
[[{"id"=>2588}], [{"id"=>2589}], [{"id"=>2590}]]

Rails: saving a string on an object -- syntax problem?

I am trying to write a simple function to clean a filename string and update the object. When I save a test string it works, but when I try to save the string variable I've created, nothing happens. But when I return the string, the output seems to be correct! What am I missing?
def clean_filename
clean_name = filename
clean_name.gsub! /^.*(\\|\/)/, ''
clean_name.gsub! /[^A-Za-z0-9\.\-]/, '_'
clean_name.gsub!(/\_+/, ' ')
#update_attribute(:filename, "test") #<-- correctly sets filename to test
#update_attribute(:filename, clean_name) #<-- no effect????? WTF
#return clean_name <-- seems to returns the correct string
end
Thank you very much.
Is the update only going through if the object ID has changed? I think it is reasonable to update the slot only when the object itself has changed.
Have you ever tried to use gsub instead of gsub!, so that the object ID changes?

Resources