Using plus signs in query strings with HTTParty - httparty

I'm trying to get this url with HTTparty:
http://collections.museumvictoria.com.au/api/search?hasimages=yes&collectingarea=royal+exhibition+building&page=1
I'm using the query:
items = get("http://collections.museumvictoria.com.au/api/search", query: {has images: "yes", collecting area: "royal+exhibition+building", page: 1})
This returns 0 results however if I just copy and past the url into a browser it does return data. From my other tests it looks as though only collecting areas with plus signs in them fail to return results collectingarea: "arms" works).
Any idea how we should properly encode the plus signs to make this work in HTTParty?

Use HTTParty version >= v0.13.4 It's encode the query values internally.
However you can Override httparty's query strings normalizer.
Also you need to put underscore between words in query keys like has_images, collecting_area.
I tested this code and it works for me:
require 'httparty'
class Test
include HTTParty
def self.test
puts self.get("http://collections.museumvictoria.com.au/api/search", query: {has_images: "yes", collecting_area: "royal+exhibition+building", page: 1})
end
end
Test.test

Related

Does gorm interpret the content of a struct with a logical OR?

New to SQL, I am writing as an exercise an API middleware that checks if the information contained in some headers match a database entry ("token-based authentication"). Database access is based on GORM.
To this, I have defined my ORM as follows:
type User struct {
ID uint
UserName string
Token string
}
In my middleware I retrieve the content of relevant headers and end up with the variables userHeader and tokenHeader. They are supposed to be matched to the database in order to do the authentication.
The user table has one single entry:
select * from users
// 1,admin,admintoken
The authentication code is
var auth User
res := db.Where(&User{UserName: userHeader, Token: tokenHeader}).Find(&auth)
if res.RowsAffected == 1 {
// authentication succeeded
}
When testing this, I end up with the following two incorrect results (other combinations are correct):
with only one header set to a correct value (and the other one not present) the authentication is successful (adding the other header with an incorrect value is OK (=auth fails))
no headers set → authentication goes though
I expected my query to mean (in the context of the incorrect results above)
select * from users where users.user_name = 'admin' and users.token = ''
select * from users where users.user_name = '' and users.token = ''
and this query is correct on the console, i.e. produces zero results (ran against the database).
The ORM one, however, seems to discard non-existing headers and assume they are fine (this is at least my understanding)
I also tried to chain the Where clauses via
db.Where(&User{UserName: userHeader}).Where(&User{Token: tokenHeader}).Find(&auth)
but the result is the same.
What should be the correct query?
The gorm.io documentation says the following on the use of structs in Where conditionals:
When querying with struct, GORM will only query with non-zero fields,
that means if your field’s value is 0, '', false or other zero
values, it won’t be used to build query conditions ...
The suggested solution to this is:
To include zero values in the query conditions, you can use a map,
which will include all key-values as query conditions ...
So, when the token header or both headers are empty, but you still want to include them in the WHERE clause of the generated query, you need to use a map instead of the struct as the argument to the Where method.
db.Where(map[string]interface{}{"user_name": userHeader, "token": tokenHeader}).Find(&auth)
You can use Debug() to check for the generated SQL (it gets printed into stderr); use it if you are unsure what SQL your code generates

Can we use '#ContinueNextStepsOnException' to run all the steps in the Karate script instead of karate.match(actual, expected)

I have a response with hundreds of attributes while matching the attributes the scripts getting failed and further steps are not getting executed. because of this we have to validate the same case multiple times to validate the attribute values. is they a option like #ContinueNextStepsOnException to execute all the steps and it is hard to script using karate.match(actual, expected) for more than 100 attributes I have give actual and expected values if in case of any failure to continue.
No, there is no such option. If your scripts are getting failed - it is because Karate is doing its job correctly !
If you feel you want to skip certain fields, you can easily do so by using match ... contains syntax.
I think you are using multiple lines instead of matching the entire JSON in one-line which you can easily do in Karate. For example:
* def response = { a: 1, b: 2 }
# not recommended
* match response.a == 1
* match response.b == 2
# recommended
* match response == { a: 1, b: 2 }
Is it so hard to create the above match, even in development mode ? Just cut and paste valid JSON, and you are done ! I have hardly ever heard users complain about this.

Baffled by nil results in ruby-dbi Oracle query

I've not played with Ruby in a while, and was just writing a simple db query tool.
The tool connects fine and returns the correct number of results for the query (56 rows in this case), but the value returned for each element is 'nil'. Executing the query in sqlplus works fine.
I've found similar problems on StackExchange, but most of the solutions don't apply, or require using ODBC directly. Ugh.
I'm including a stripped down version of what I've written. Any ideas what I'm doing wrong?
require 'dbi'
dbh = DBI.connect('DBI:OCI8:foodb', 'user', 'password')
rs = dbh.prepare('select field_name from foo_user.cdr_fields where layout like ?')
rs.execute('phi_outage')
while rsRow = rs.fetch do
p rsRow
end
rs.finish
dbh.disconnect
The fetch method is an iterator so no need for a while loop. Try
rs.fetch do|row|
p row unless p.nil?
end
The API states that the method gets called for all remaining rows and will return nil when done.

ActiveRecord search model using LIKE only returning exact matches

In my rails app I am trying to search the Users model based on certain conditions.
In particular, I have a location field which is a string and I want to search this field based on whether it contains the search string. For example, if I search for users with location 'oxford' I want it to also return users with a variation on that, like 'oxford, england'.
Having searched the web for the answer to this it seems that I should be using the LIKE keyword in the activerecord search, but for me this is only returning exact matches.
Here is a snippet of my code from the search method
conditions_array = []
conditions_array << [ 'lower(location) LIKE ?', options[:location].downcase ] if !options[:location].empty?
conditions = build_search_conditions(conditions_array)
results = User.where(conditions)
Am I doing something wrong? Or is using LIKE not the right approach to achieving my objective?
You need to do like '%oxford%'
% Matches any number of characters, even zero characters
conditions_array << [ 'lower(location) LIKE ?', "%#{options[:location].downcase}%" ] if !options[:location].empty?

Rails 3 after_save old value

How do you work with the old values of a record being updated?
For instance in the following code block how would I run a query using the previous winner_id field after I determine that it has indeed changed?
if self.winner_id_changed?
old_value = self.changed_attributes
User.find(old_value)
#do stuff with the old winner....
end
An example output of self.changed_attributes would be:
{"winner_id"=>6}
Do I really have to convert this to a string and parse out the value in order to perform a query on it? old_value[:winner_id] doesn't seem to do anything.
Use where instead of find, and the following inject method on changes to generate the desired hash:
if self.winner_id_changed?
old_value = self.changes.inject({}) { |h, (k,v)| h[k] = v.first }
old_user = User.where(old_value)
#do stuff with the old user....
end
You can also use ActiveRecord dirty methods such as:
self.winner_id_was
to get specific attribute's old value. Full documentation may be found here.