How can I turn a mongoid document into JSON stripping out embedded document ids, but keeping the main document id? - ruby

I have a document that has some embedded documents (and some of those have further embedded documents).
I want to return the document content as JSON but without all the IDs for the embedded documents.
I can do this: mydoc.to_json(:except => :_id)
but that strips all BSON IDs, including the one for mydoc.
Is there some other way to only strip the embedded document IDs?

Keep in mind that to_json is actually two steps here:
Call as_json to get a Hash.
Convert that Hash to a string of JSON.
So you could use as_json instead of to_json to build a Hash without any _ids, then put the _id you care about back in, and finally convert to JSON:
mydoc.as_json(:except => :_id).merge('_id' => mydoc.id).to_json

Related

Ruby Find a value in a complex JSON object

I need to find the value of a particular key (say "key") in a JSON object. Since I am getting the JSON object dynamically, I do not know the structure of the JSON object.
Could anyone tel me an easy way to find the value of a key in such a JSON object?
If you dont know the structure of the JSON then you will need to do more work to inspect all possible keys.
You might just have to do a recursive descent and iterate over all keys until you find the key whose name matches key and then grab its value.

CouchDB Query View with Multiple Keys Formatting

I'm having a problem getting a couchdb view to return the proper documents when using multiple keys.
This works fine, returning the documents that match:
GET http://example.com:5984/myDb/_design/myFilters/_view/getItemByForeignKeyId?key=abc123
This returns returns all documents in the view, matching or not:
GET http://example.com:5984/myDb/_design/myFilters/_view/getItemByForeignKeyId?keys=%5B%22abc123%22%5D
I'm usually very good at hunting down my answers. But, CouchDB documentation is very clear on the format for using multiple keys. I've seen some use the ?keys=[123,123] and i've also seen ?keys="abc","abc".
If anyone can offer any clarification on the 'proper' format and encoding of multiple key queries for CouchDB using a GET method, I would be extremely appreciative.
To get multiple keys from a view, you need to do a post request and submit the keys in the request body. Your HTTP request will look like this:
POST /myDb/_design/myFilters/_view/getItemByForeignKeyId
Content-Type: application/json
{
"keys" : [
"abc",
"123"
]
}
function(doc){
{
if([doc.key1, doc.key2])
emit([doc.key1, doc.thingYouWantToKnow]);
}
}
and in the query string, at the end
?key=["key1Value", "key2Value"]
Notice that it is key=[], not keys=[] !!!!!!!!!
Not saying it's correct, but you can actually do it via query string as well. The array enclosing brackets should not be encoded. E.g. this works for me:
http://localhost:5984/test/_design/artists_albums/_view/albums_by_artist?keys=[%22Super%20bad%20artist%22,%20%22Fake%20artist%201%22]

Check if a favorited tweet contains a URL within the body

Building a small app and would like to return all a users favorited tweets. This is easy enough to do with the twitter gem. I would then like to further filter the returned results by only displaying the favorited tweets that contain a URL within the body.
Now as I understand it Using the the twitter gem running Twitter.favorites will return a json of all the favorited tweets. Now within each of the individual tweets it returns a entity property that contains a URL hash this will be empty if no URL is present in the tweet and a URL if one is present.
How would I implement a check to say if the URL is present then display tweet. I'm a noob with json and Apis.
I never used the twitter gem, but since the question remains unanswered for a couple of hours, I’ll try to do my best.
First of all the gem seems to return Array<Twitter::Tweet> rather than raw json. So you only need to filter the array:
favs_with_urls = Twitter.favorites.reject { |r| r.urls.empty }
The latter should do the trick.
BTW, if you for some reason need to parse json to a hash:
require 'json'
c = JSON.load(raw_json)

Redis-rb pushing hash into list

Using redis-rb, how can I push a hash into a list? Do I have to JSON encode it or is this natively supported? If so, how can I do it? I only see hset method with a key and key/value pairs.
Thanks
Storing any object (not just hash) as a JSON encoded string is one way to do it.
If your use case allows it you can also store hash IDs within the list and use SORT GET to retrieve additional values.
Example:
r.hmset('person:1', 'name','adam','age','33')
r.hmset('person:2', 'name','eva','age','28')
r.lpush('occupants', 'person:1')
r.lpush('occupants', 'person:2')
r.sort('occupants', :get => ['*->name'])
To get list names from hashes which IDs are stored within occupants list. You can retrieve multiple fields, but you will get only array back.
For more information check SORT command
A Redis list is analogous to a Ruby Array. It has no keys.
As discussed in the redis-rb documentation, if you want to store a Ruby object in a Redis value you'll need to serialize it first using e.g. JSON:
Storing objects
Redis only stores strings as values. If you want to store an object inside a key, you can use a serialization/deseralization mechanism like JSON:
>> redis.set "foo", [1, 2, 3].to_json
=> OK
>> JSON.parse(redis.get("foo"))
=> [1, 2, 3]
Your other option would be to store it as a Redis hash, as you mentioned, using e.g. HMSET, but if your only goal is to store and retrieve the object (rather than perform Redis operations on it), that's superfluous.

What to call a method that finds or creates records in db

This question might seem stupid but i nonetheless i believe it's a worth asking questioin.
I work on some web application when we use tags which are attached to articles.
When adding new article users provides a list of tags he wish to associate with his new article.
So when the form is submitted and my MVC controller processes request i have a string with tags from the form. I split the tags string and i get an array of tag words. Then i need a
list o tags ids from db. So i came up with a method that takes a list of tag words and checks if each tag already exists in db. If given tag is already in db then tag's id is appended to result array. If tag does not exist in db it is created and then id of just created tag is appended to result array.
My question is: what is the best name for such a method? This method creates tags only if necessary and returns list of tags' ids.
I tried this names, but none of them looks right to me:
fetchTagsIds(List tagWordsList)
createOrFindsTagsIds(List tagWordsList)
obtainTagsIds(List tagWordsList)
I need a name that really reflects what the method does. Thanks for your help :)
I'd drop the "s" in "Tags". So that the method is:
FetchTagIds(List tagWordsList)
IdsOfTags. That it creates them is an implementation detail (as is the fact that it uses a relational database in the first place). All that matters is that it gives you unique ids for tags (e.g. it could also hash them with a perfect hash function, or lookup an ID in the web.
If you're having trouble coming up with a name that accurately describes what your method does, that could be because you method does too much. Perhaps it would be better to refactor it into two:
findTagsByName(List tagNames) would return a list of Tag objects based on list of names you pass in
persistTags(List tags) - or saveTags(), or createTags() - would persist a list of Tag objects.
getTagIDs?
Get suggests that the code will do something to get an ID when one doesn't exist to fetch.

Resources