Grails print each in attribute[]: [1,2,3] - grails

Below, is what returning on my server:
[test[]:[1, 2, 3, 4, 5], action: something, controller: myController]
And I can't println using
params.test.each{ println it}
How can I print on each element in test[]?

The issue you are having is that the key named test[] needs to be escaped.
Thus you should be able to do:
params."test[]".each { println it }
The reason for needing to use double or single quotes around the property name is due to the fact you have brackets in the name of the property. Usually brackets appearing in Groovy code would be seen as a collection and without an index or key within the brackets it's considered invalid syntax.
So, in this case since the name of the property/key within your params contains brackets you need to wrap it in quotes so Groovy understands it's just part of the name/key and not an attempt to access it as a collection (even if your property is actually a collection).
Honestly, I would fix the root of the issue, meaning don't name your property test[] but rather test since it's much cleaner and clearer as to what your property actually is.

Related

Dynamic variable name with dashes in thymeleaf

I am trying to create a variable name in thymeleaf by using another variable as prefix:
th:with="appOverview = ${__${tabId}__AppOverview}"
It works most of the times, but in the case where tabId contains dashes (i.e., "my-test-tab"), thymeleaf throws the following exception:
The operator 'SUBTRACT' is not supported between objects of type 'null' and 'null'
I guess that the dashes confuse thymeleaf into believing it's an arithmetic operation between non-existing variables.
I tested adding a variable with th:with="my-var='bad dashes'" and it worked fine, so I suppose dashes are generally accepted as characters in variable names.
Is there a way to tackle this issue?
Ah, I finally found it!
The thing I was missing is that all model variables are stored in thymeleaf in the #vars object, so accessing them from there won't confuse thymeleaf. Here's what worked:
th:with="appOverview = ${#vars.get('__${tabId}__AppOverview')}"

Ruby on Rails: How may create a quoted string to a request header?

I am writing from scratch a Twitter client and one of the requisites is not using Twitter gems, so I must create my own requests.
Twitter API documentation says here that I must have a Authorization header like this:
Authorization:
OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog",
oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318622958",
oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb",
oauth_version="1.0"
As you may see I must have something like oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog" with the second part in quotes. I tried using %Q like in
["oauth_consumer_key",%Q( Figaro.env.TWITTER_ACCESS_TOKEN )].join('=')
assuming %Q would return a quoted string. but when I inspect the value, all I get is
oauth_consumer_key=xvz1evFS4wEEPTGEFPHBog
which, obviously, is different from the required result.
What am I missing?
1. My solution:
'oauth_consumer_key="#{Figaro.env.TWITTER_ACCESS_TOKEN}"'
2. Why:
%Q() basically replaces the variable with double quotes "", it is literally the same as if you wrote "Figaro.env.TWITTER_ACCESS_TOKEN"
In fact, to display the content of a variable, you have to use interpolation
instead of the name itself, using "#{var}".
You can also use %Q directly with interpolation using %Q{var} (note {} instead of ()).
Your problem is elsewhere: with the join() method. It's getting rid of double quotes. In that case doing ["var", var].join('=') and ["var", %Q{var}].join('=') ends doing exactly the same thing but more complicated.
#Artem Ignatiev's solution should works. But if you need to be more readable, you don't even need to join, imho, it makes sense only when you are using more than two variables.
For instance, I will use something like 'oauth_consumer_key="#{var}"' mixing single and double quote to make sure it causes no confusions.
If you do need to use %Q() and join, you can still use ["oauth_consumer_key", %Q("#{Figaro.env.TWITTER_ACCESS_TOKEN})].join('=').
Note that because of the join you can use single quote interpolation %q or double quote interpolation %Q without affecting the ends results:
e.g
['oauth_consumer_key', %q("#{var}")].join('=') == ["oauth_consumer_key", %Q("#{var}")].join('=')
%Q(x) is basically the same as "x".
To achieve the desired result you have to manually introduce quotes into %Q expression, like this: %Q("#{Figaro.env.TWITTER_ACCESS_TOKEN}")

How do i remove 'quotes' from strings that can contain single quotes?

I have params that is returning 4, 36, 'new tag', 52, 'Mcdonald\'s', 25 as a string.
I then split them by , and then i need to do some work on them.
First, I need to create a new tag based on that, but i need to somehow gsub (or something?) the outside quotes, but not the inner ones (if the tag contains it, like McDonald's above)
Second, I need to unescape the \ that the token input adds. I'm not sure how to do that second step so its the best security-wise
PS. I have validations on that model so I'm hoping that's good enough and i dont have to worry about some kind of SQL injection thing
params.split(/,\s+/).map{|s| s.start_with?("'") && s.end_with?("'") ? s[1..-2] : s }
That should clear up the first part about quotes.

Fitnesse test against empty string result

I'm using Fitnesse SliM and I want to check if the result of a fixture is the empty string. Leaving the result field in Fitnesse empty just results in an ignored test which is obviously not what I want. I could solve this by extending the fixture code, but I wonder if this can be handled within Fitnesse itself.
It seems that Slim implies an empty string as an ignore, at least for the QueryTable fixture: A cell that is left blank in the table will be filled in from the result and counted as ignored.
Even though this is not considered a good solution, if you really have to you could use a regular expression to test on an empty string by matching on
=~/^$/
Another option is using the null fixture driver, as seen in http://fitnesse.org/FitNesse.SuiteAcceptanceTests.SuiteSlimTests.SlimSymbolsCanBeBlankOrNull
passing the word 'blank' simulates a empty string.
like:
|Check|That the returned string is | blank |
In this case - when you need to check with SLIM usage, whether the result is an empty string, you can use markup variable. Just define it somewhere on your page with test, like:
!define blank {}
And then call it anywhere you want:
|check|SomeFixtureName|${blank}|

Help interpreting this bit of Rails code

What is this?
"#{h params[:chat_input]}"
I am referring to the hash # and the h.
Most likely this is inside a double-quoted string, such as "Ponies all love #{h params[:chat_input]}!" The #{stuff} expression causes the stuff expression to be interpreted and inserted into the string. For example "1 + 2 = #{1 + 2}" will result in the string "1 + 2 = 3".
The h is an alias to the html_escape method, which is pretty self-explanatory.
The code you paste, by itself, is just a comment. I assume the code is inside a string, though.
"hello, #{5 + 5}"
# => hello, 10
The statement inside the brackets will be evaluated as Ruby. This is called string interpolation.
The statement inside the interpolation in your code is a method that gets an argument.
h params[:chat_input]
h(params[:chat_input])
The h method is a shortcut for html_escape, which escapes HTML. For example, <span> is converted into <span>, so that the browser displays the actual contents of the string, instead of interpreting it as HTML.
html_escape(params[:chat_input])
You probably know what params is.
To sum up, you get a HTML escaped version of whatever params[:chat_input] contains.
"#{h params[:chat_input]}"
In ruby, double-quoted strings allow for expressions to be evaluated and automatically converted to strings.
I can do this:
years = 25
"John is " + years + " years old"
but I'll get an error because I can't add the number to a string.
I can do
"John is #{years} years old"
to get around that.
The h() method is a Rails helper function that removes HTML tags. It's a safety thing.
Finally, params() is a method in Rails that gives you access to GET and POST parameters. It's actually wrapping a hash GET and POST parameters are symbolized to reduce memory (symbols are only defined once, whereas a string like "foo" is a new object every time.)
So, params[:chat_input] retrieves the value from the previous request's GET or POST parameters, and in your case it looks like it's just displaying and sanitizing them.
Hope that helps!
It's just interpolating a value inside a string. The :chat_input is a symbol, it's used in place of a string because symbols are only created once.
h(something)
or
h something
since ruby does not force the use of (), is a function available in rails that converts the parameter to a "safe HTML" string avoiding interpreting the possible HTML code inside of the 'something' variable.
"#{x}"
in ruby means converting the x variable to a string and placing it in the new string for example:
"#{host}:#{port}"
will place the value of host and the value of port into the new string formed by the "", in a way that if host is "localhost" and port is 30 the result string will be "localhost:30"
params is a special rails hash that contains the post/get parameters passed to the controller method being executed
another detail is that in ruby a method always returns the last evaluated expression
so the method
def test
"#{h params[:chat_input]}"
end
will return a string that has the HTML-safe value of the post/get parameter chat_input
holy crap, is that from chat_sandbox by any chance?
if so, let me know if you need any help $)
I'm hoping to update that code here soon.

Resources