read an array on ruby on rails - ruby-on-rails

I'm trying to read this array on RoR:
> importer_name = [#<RouteImporter id: 1, name: "aa", filename: "aa1", type: "RouteImporter">]
I just want to get the filename character "aa1", I tried with importer_name[2] but I didn't get nothing and I don't want 'filename: "aa1"' I just want "aa1", any idea? Thanks in advance!

you have a Ruby object stored in an array. You can access it like this(If I understand you correctly):
importer_name.first.filename

Related

Get price from variants object with shopify_api - and ruby on rails

I'm using shopify_api (https://github.com/Shopify/shopify_api) to create an app for Shopify using Ruby.
For a Base::Product, by calling directly product.variants, i will have:
[#<ShopifyAPI: :Variant: 0x00007fa15cb0e960 #attributes={
"id"=>12664776392816,
"title"=>"Default Title",
"price"=>"5.00",
"sku"=>"",
"position"=>1,
"inventory_policy"=>"deny",
"compare_at_price"=>nil,
"fulfillment_service"=>"manual",
"inventory_management"=>nil,
"option1"=>"Default Title",
"option2"=>nil,
"option3"=>nil,
"created_at"=>"2018-08-27T03:17:24-04:00",
"updated_at"=>"2019-04-07T23:52:00-04:00",
"taxable"=>true,
"barcode"=>"",
"grams"=>0,
"image_id"=>nil,
"weight"=>0.0,
"weight_unit"=>"kg",
"inventory_item_id"=>12758757474416,
"inventory_quantity"=>0,
"old_inventory_quantity"=>0,
"requires_shipping"=>true,
"admin_graphql_api_id"=>"gid://shopify/ProductVariant/12664776392816"
}, #prefix_options={
:product_id=>1389200408688
}, #persisted=true>
]
In this case, how do I directly get price attribute from this json returned
EDIT:
I just jump in ruby on rails in the middle, so here is what I have tried so far:
product.variants.prices --> in my guts it definitely does not work, but might as well trying
returns with undefined methodprice' for #`
parse the JSON
1) JSON.parse(product.varient)['price']
returns with
no implicit conversion of Array into String
2) variant = ActiveSupport::JSON.decode(product.variants[0])
or variant = ActiveSupport::JSON.decode(product.variants)
then
variant['price']
but both return with no implicit conversion of ShopifyAPI::Variant into String
product = ShopifyAPI::Product.find(shopify_product_id)
product.variants.map(&:price)
it will give you an array of price because product might have multiple variants.
you can also use .pluck method instead of .map

Map object and nested object to model using Ruby on Rails

I have an object like
{"Result":[{
"Links":[{
"UrlTo":"http://www.example.com/",
"Visited":1364927598,
"FirstSeen":1352031217,
"PrevVisited":1362627231,
"Anchor":"example.com",
"Type":"Text",
"Flag":[],
"TextPre":"",
"TextPost":""
}],
"Index":0,
"Rating":0.001416,
"UrlFrom":"http://www.exampletwo.com",
"IpFrom":"112.213.89.105",
"Title":"Example title",
"LinksInternal":91,
"LinksExternal":51,
"Size":5735
}]}
And I have a model with all of the keys.
UrlTo, Visited, FirstSeen, PrevVisited, Anchor, Type, TextPre, TextPost, Index, Rating, UrlFrom, IpFrom, Title, LinksInternal, LinksExternal, Size
I understand how to save this to the database without this bit below...
"Links":[{
"UrlTo":"http://example.com/",
"Visited":1364927598,
"FirstSeen":1352031217,
"PrevVisited":1362627231,
"Anchor":"example.com",
"Type":"Text",
"Flag":[],
"TextPre":"",
"TextPost":""
}],
Not sure how to save it with a nested object as well.
I had a search on Google and SO and couldn't find anything, what is the correct way to do this? Should I move the nested object into the one above? I have no need for it to be nested...
Thanks in advance
it looks like you want to save links, so I would loop over the Result/Links in the json provided, and create a new hash based on the links.
I've pretended below that your json is in a file called input.json -- but you'd obviously just parse the text or use an existing JSON object
require 'json'
json = JSON.parse File.read("input.json")
links = json["Result"].map do |result|
result["Links"].map {|link| link }
end.flatten
hash = {"Links" => links}
puts hash
This creates the object:
{"Links"=>[{"UrlTo"=>"http://www.example.com/", "Visited"=>1364927598, "FirstSeen"=>1352031217, "PrevVisited"=>1362627231, "Anchor"=>"example.com", "Type"=>"Text", "Flag"=>[], "TextPre"=>"", "TextPost"=>""}]}

Mapping to the Keys of a Hash

I am working with a hash called my_hash :
{"2011-02-01 00:00:00+00"=>816, "2011-01-01 00:00:00+00"=>58, "2011-03-01 00:00:00+00"=>241}
First, I try to parse all the keys, in my_hash (which are times).
my_hash.keys.sort.each do |key|
parsed_keys << Date.parse(key).to_s
end
Which gives me this :
["2011-01-01", "2011-02-01", "2011-03-01"]
Then, I try to map parsed_keys back to the keys of my_hash :
Hash[my_hash.map {|k,v| [parsed_keys[k], v]}]
But that returns the following error :
TypeError: can't convert String into Integer
How can I map parsed_keys back to the keys of my_hash ?
My aim is to get rid of the "00:00:00+00" at end of all the keys.
Why don't you just do this?
my_hash.map{|k,v| {k.gsub(" 00:00:00+00","") => v}}.reduce(:merge)
This gives you
{"2011-02-01"=>816, "2011-01-01"=>58, "2011-03-01"=>241}
There is a new "Rails way" methods for this task :)
http://api.rubyonrails.org/classes/Hash.html#method-i-transform_keys
Using iblue answer, you could use a regexp to handle this situation, for example:
pattern = /00:00:00(\+00)+/
my_hash.map{|k,v| {k.gsub(pattern,"") => v}}.reduce(:merge)
You could improve the pattern to handle different situations.
Hope it helps.
Edit:
Sorry, iblue have already posted the answer
Another alternative could be:
map
return converted two elements array [converted_key, converted_value]
convert back to a hash
irb(main):001:0> {a: 1, b: 2}.map{|k,v| [k.to_s, v.to_s]}.to_h
=> {"a"=>"1", "b"=>"2"}

Ruby On Rails: Accessing Array?

I have an array stored in a variable temp which looks like this:
temp.inspect output :
[#"Marlana Letelier", "completed_at"=>nil, "status"=>"incomplete", "name"=>nil, "lead_move_date"=>"2012-06-17 00:00:00", "archive_time"=>nil, "stop_time"=>nil, "priority"=>"2", "assigned_to_user_firstname"=>"Vanessa", "notes"=>"", "created_by_id"=>nil, "id"=>"804005", "assigned_to_id"=>"1", "dn_email_id"=>nil, "outcomes_string"=>"other", "lead_id"=>"101139", "flavor"=>"PhonecallTask", "stringified_parameters"=>"{\n'purpose' => 'continued contact attempt',\n'phone_number' => '361-946-9905',\n}", "created_at"=>"2011-12-21 13:29:07", "start_time"=>"2012-04-04 17:00:00"}>]
temp.class specifies it as an array but temp[1] doesn't output anything.
How do I access the elements ?
EDIT:
1) Temp either had nothing, 1 object or multiple objects
2) Check for nil
3) Get each object out
4) access the attributes
Although your inspect output looks wrong (I think you're missing some text that came out in <...> tags) it looks like you have an array with a single item. Verify this assumption by outputting temp.length.
Since Arrays in Ruby are 0-indexed, try temp[0] or temp.first.

mongodb: converting object ID's to BSON::ObjectId

We have recently upgraded our application to Rails3 and we are now using Mongoid, and we have a problem retrieving previous documents from mongo-db by _id.
Upon closer investigation, an old record (which I can't retrieve by _id) look as follows:
#<Audit::Log _id: 4d892bfe6bcaff4ffd000001,
failed: nil, request_id: "68ccb38e9e345bb7fc55331389a902a1",
session_id: "54940ff7e8c7336d813a872db7cb7bc0",
_id: "4d892bfe6bcaff4ffd000001", ... }>
and a good record has the following structure:
#<Audit::Log _id: 4d892bfe6bcaff4ffd000001,
failed: nil, request_id: "68ccb38e9e345bb7fc55331389a902a1",
session_id: "54940ff7e8c7336d813a872db7cb7bc0",
_id: BSON::ObjectId('4d892bfe6bcaff4ffd000001'), ... }>
As you can see, the _id field is different. For the old records it seems to be just a string, and for the new records it is a BSON::ObjectID.
I can't seem to be able to retrieve the records with the old format. Trying to find the records using
Audit::Log.where(:_id => BSON::ObjectId('4d892bfe6bcaff4ffd000001')).first
Audit::Log.where(:_id => '4d892bfe6bcaff4ffd000001').first
both return nil.
But for the good record, I can just do
Audit::Log.where(:'_id' => '4e14152d6bcaff26bb000039').first
I am guessing, but maybe Mongoid automatically converts the string to an ObjectId to find on _id? The only fix I see would be to convert
all the _id-fields to BSON::ObjectId if they are not already. But how do I do that?
Or do you have a better approach?
All of these will work, provided the record actually exists:
Account.where(:_id => "4e0a9c6142f5bc769f000008").first
Account.find(BSON::ObjectId("4e0a9c6142f5bc769f000008"))
Account.find("4e0a9c6142f5bc769f000008")
I'm interested in the JSON returned about a Audit::Log... Why are there two _id fields returned?
#<Audit::Log _id: 4d892bfe6bcaff4ffd000001,
failed: nil, request_id: "68ccb38e9e345bb7fc55331389a902a1",
session_id: "54940ff7e8c7336d813a872db7cb7bc0",
_id: "4d892bfe6bcaff4ffd000001", ... }>
You may want to drop to the mongo driver and see if this log truly exists in the database. Unless you are declaring another "_id" field in the audit_log.rb, I believe this record does not exist.
Ha, I should have looked further at the Mongoid documentation. They have a section describing how to upgrade. In the section to upgrade to 2.0.0.BETA.11 + they describe that the _id's now no longer are String and they point to this gist to convert all your ids from string to ObjectId.
Ex: Here is an id
1.9.3-p125 :096 > profile_id
=> “4fe969dd79216d0af9000002″
1.9.3-p125 :099 > BSON::ObjectId.from_string(profile_id)
=> BSON::ObjectId(’4fe969dd79216d0af9000002′)

Resources