Hi.
I have an object in Ruby called Post. I would like to convert post into an json but also I want to include the name of the user who posted the post. The thing is user_name is not present in Post object but the user id is.
So what I effectively want is something like this
{name:"My Post", body:"My post data", user_name:"jhonny"}
When I do a to_json on Post object I get following
{name:"My Post", body:"My post data"}
But I also want to append user_name:"jhonny"
part also to it. I know I can make it a hash and then do a to_json
on the hash, but I do not want to make the hash for all the post values manually as there are many attributes to post. I'd rather user a hash merge function to add the additional attribute to hash and then call json on it.
Is there a way to make a quick hash object for a ruby class? Any ideas will be welcome.
Something like
my_post.hash.merge{:user_name => "jhonny"}.to_json
Cheers.