Mongoid 3 bulk updates - ruby-on-rails

Bulk updates are no longer working after upgrading to Mongoid 3. In Mongoid 2, I had the following:
Shift.where(
:account_id => current_account.id,
:location => self.department.location.name,
:department => self.department.name,
:position => self.name_was,
:color => self.color_was,
:date.gte => Date.current
).update_all(position: self.name, color: self.color)
I know the criteria is returning results but it no longer updates the documents. Here's the statement in Mongoid 3:
Shift.where(
:account_id => current_account.id,
:location => self.department.location.name,
:department => self.department.name,
:position => self.name_was,
:color => self.color_was,
:date.gte => Date.current
).update(position: self.name, color: self.color)
I'm running Rails 3.2.7 and Mongoid 3.0.3. Has anything changed that I'm not aware of? Also here's the entry from the logs:
MOPED: 127.0.0.1:27017 UPDATE database=development collection=shifts selector={"$query"=>{"account_id"=>"5017e8774f4e481fe3000001", "location"=>"Downtown", "department"=>"Cashes", "position"=>"Cash 1", "date"=>{"$gte"=>2012-08-01 00:00:00 UTC}}, "$orderby"=>{"start_at"=>1}} update={"$set"=>{:position=>"Cash A", :color=>"#42ed23"}} flags=[:multi] (0.2141ms)
However, nothing gets updated in the database.

I think it's because your query use a String like account_id, not a Moped::BSON::ObjectId.
If you do the where without the update. You have no result I supposed.

Related

How do I access "request" and "session" objects from within my rspec tests?

I have a Rails 4.2 application that does different business depending on host name. I know this practice is frowned upon in certain circles but I managed to get the same code base working on about 400 websites, the amount of time|cpu|ram|db|money|squirrels saved is tremendous.
Eg:
For www.example.com for user john#doe.com it might show Product 1 with a $5000 price tag;
For www.blah.com for all usrs it might show Product 1 with a $123 price tag. And a shipping fee of $400.
This is all based on host name and a number of variables stored into session when users visit and/or log in to the website.
I'd like to write a bunch of specs to test various aspects of the application but I need to be able to set the request.host, format and some things in the session.
How do I get this done?
Later edit:
I managed to do a find and replace through the source code and get the session/request access done from within some helper methods. Now I can stub within my specs as follows:
allow_any_instance_of(ApplicationHelper).to receive(:detect_user_info_by_ip).with("ip").and_return( { :provider => "dummy", :ip => "127.0.0.1", :lat => 1.0, :latitude => 1.0, :lon => 2.1, :long => 2.1, :longitude => 2.1, :regi
on => "EU", :country => "GB", :city => "Testville", :country_iso2 => "GB", :success => true} )
allow_any_instance_of(ApplicationHelper).to receive(:detect_user_info_by_ip).and_return( { :provider => "dummy", :ip => "127.0.0.1", :lat => 1.0, :latitude => 1.0, :lon => 2.1, :long => 2.1, :longitude => 2.1, :region => "EU",
:country => "GB", :city => "Testville", :country_iso2 => "GB", :success => true} )
Bottom line is: easier to refactor and stub than access the request and session objects from within specs.

Fedex Plugin Rails

I working on an existing code base for a client. The app is built in rails 2.3 and uses the fedex plugin. Now i have develop a functionality for shipping the goods using international priority service type, the problem i'm facing is when ever i make a call to the fedex api for a shipping label it returns an error
"Fedex::FedexError: Unable to get label from Fedex: Customs Value is required"
Can some one help me how to mention the customs value for the label.
This is how my code is:
price, labels, tracking_number = fedex.label(
:shipper => { :contact => shipper, :address => origin },
:recipient => { :contact => recipient, :address => destination.merge(:residential => false) },
:service_type => service_type,
:packages => [{:length => 3,
:height => 4,
:width => 5,
:weight => 5,
}],
:weight => 5,
:commodities => commodities,
:customs_value =>{:currency => "USD", :amount => "100" },
:residential => is_residential_destination
)
Thanks in advance.

'Encoding::UndefinedConversionError "\xE9" from ASCII-8BIT to UTF-8' when using some ruby gems that using file.open in ruby on rails

What's I want?
I want to generate .docx file or .odt file from template file in Rails 3.2
I want to use Japanese in it.
In ubuntu server 12.04 & ruby 1.9.3p194 & rails 3.2.8
What's happen?
I tried gems 'docx-templater' and 'serenity'
ruby-docx-templater
https://github.com/jawspeak/ruby-docx-templater
1 sample works good
2 try to do the same in my rails app
in controller as is sample
def gen_docx
input_file = './app/template/ExampleTemplate.docx'
data = {
:teacher => "Priya Vora",
:building => "Building #14",
:classroom => :'Rm 202',
:district => "Washington County Public Schools",
:senority => 12.25,
:roster => [
{:name => 'Sally', :age => 12, :attendence => '100%'},
{:name => :Xiao, :age => 10, :attendence => '94%'},
{:name => 'Bryan', :age => 13, :attendence => '100%'},
{:name => 'Larry', :age => 11, :attendence => '90%'},
{:name => 'Kumar', :age => 12, :attendence => '76%'},
{:name => 'Amber', :age => 11, :attendence => '100%'},
{:name => 'Isaiah', :age => 12, :attendence => '89%'},
{:name => 'Omar', :age => 12, :attendence => '99%'},
{:name => 'Xi', :age => 11, :attendence => '20%'},
{:name => 'Noushin', :age => 12, :attendence => '100%'}
],
:event_reports => [
{:name => 'Science Museum Field Trip', :notes => 'PTA sponsored event. Spoke to Astronaut with HAM radio.'},
{:name => 'Wilderness Center Retreat', :notes => '2 days hiking for charity:water fundraiser, $10,200 raised.'}
],
:created_at => "11-12-03 02:01"
}
DocxTemplater::DocxCreator.new(input_file, data).generate_docx_file()
end
3 but the error raised
the error raised at following point in gem (docx_templater.rb 22)
File.open(file_name, 'w') { |f| f.write(buffer) }
serenity
https://github.com/kremso/serenity
1 sample works well
2 do the same in my rails app and works well
like this
#encoding: utf-8
require 'serenity'
class Showcase
include Serenity::Generator
Person = Struct.new(:name, :items)
Item = Struct.new(:name, :usage)
def generate_showcase
#title = 'Serenity inventory'
mals_items = [Item.new('Moses Brothers Self-Defense Engine Frontier Model B', 'Lock and load')]
mal = Person.new('Malcolm Reynolds', mals_items)
jaynes_items = [Item.new('Vera', 'Callahan full-bore auto-lock with a customized trigger, double cartridge and thorough gauge'),
Item.new('Lux', 'Ratatata'),
Item.new('Knife', 'Cut-throat')]
jayne = Person.new('Jayne Cobb', jaynes_items)
#crew = [mal, jayne]
render_odt 'app/template/showcase.odt'
end
end
3 I tried my template including Japanese but the error raised.
the error raised at following point in gem(template.rb 22)
def process context
tmpfiles = []
Zip::ZipFile.open(#template) do |zipfile|
%w(content.xml styles.xml).each do |xml_file|
content = zipfile.read(xml_file)
odteruby = OdtEruby.new(XmlReader.new(content))
out = odteruby.evaluate(context)
tmpfiles << (file = Tempfile.new("serenity"))
file << out #!!!! HERE !!!!
file.close
zipfile.replace(xml_file, file.path)
end
end
end
What I did?
I found that 'serenity' have rspec test for Greek (UTF-8) in gem.I tried Japanese the same way. and the test passed!. so I thought the problem is not in gems in rails setting.
add magic comment "#encoding: utf-8" to my controller or lib file
confirm 'config.encoding = "utf-8"' in config/application.rb
add following to config/enviroment.rb above "initialize!"
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
I don't use any database in my rails app.
But all is nothing to do with my case... any idea?
I may not know the basic things ...
This is a little old, but I just ran into this same situation. In my case, it was a matter of setting the tempfile to binary mode prior to writing to it:
tmpfiles << (file = Tempfile.new("serenity"))
file.binmode
file << out
file.close
Hope this helps

Ruby add_item for eBay

I am attempting to write a ruby on rails app that posts an item to eBay. Cody Fauser/Garry Tan have a gem called ebayApi which is built on top of the ebay gem. When I attempt to post an item, I am getting an error back from ebay that says the condition ID is required for this category. I have found a category that does not require the condition, and I can post to that category. Searching through the eBay API documentation, I have found a tag conditionID under the "item" class. However, in the documentation for ebayAPI, there is no such tag. Looking back at the ebay API documentation, there is an older way to specify condition, using lookup_attributes. I have noted that the return xml is coming in API version 745, and Garry Gan's updated of the ruby interface is running version 609. I have tried using the lookup, and seem to get the same error (condition required). I am using the following code to specify the item:
#ebay = Ebay::Api.new :auth_token => #seller.ebay_token
item = Ebay::Types::Item.new( :primary_category => Ebay::Types::Category.new(:category_id => #ebayTemplate.categoryID),
:title => #ebayTemplate.name,
:description => #ebayTemplate.description,
:location => #ebayTemplate.location,
:start_price => Money.new((#ebayTemplate.startPrice*100).to_d, #ebayTemplate.currency),
:quantity => 1,
:listing_duration => #ebayTemplate.listingDuration,
:country => #ebayTemplate.country,
:currency => #ebayTemplate.currency,
:payment_methods => ['VisaMC', 'PayPal'],
:paypal_email_address => '********#gmail.com',
:dispatch_time_max => 3,
:lookup_attributes => [Ebay::Types::LookupAttribute.new( :name => "Condition", :value => "New")],
# :attribute_sets => [
# Ebay::Types::AttributeSet.new(
# :attribute_set_id => 2919,
# :attributes => [
# Ebay::Types::Attribute.new(
# :attribute_id => 10244,
# :values => [ Ebay::Types::Val.new(:value_id => 10425) ]
# )
# ]
# )
# ],
:shipping_details => Ebay::Types::ShippingDetails.new(
:shipping_service_options => [
# ShippingServiceOptions.new(
# :shipping_service_priority => 2, # Display priority in the listing
# :shipping_service => 'UPSNextDay',
# :shipping_service_cost => Money.new(1000, 'USD'),
# :shipping_surcharge => Money.new(299, 'USD')
# ),
Ebay::Types::ShippingServiceOptions.new(
:shipping_service_priority => 1, # Display priority in the listing
:shipping_service => #ebayTemplate.shipSvc,
:shipping_service_cost => Money.new((#ebayTemplate.shipSvcCost*100).to_d, #ebayTemplate.currency),
:shipping_surcharge => Money.new((#ebayTemplate.shipSurcharge*100).to_d, #ebayTemplate.currency)
)
],
:international_shipping_service_options => [
Ebay::Types::InternationalShippingServiceOptions.new(
:shipping_service => 'USPSPriorityMailInternational',
:shipping_service_cost => Money.new((#ebayTemplate.shipSvcCost*100).to_d, #ebayTemplate.currency),
:shipping_service_priority => 2,
:ship_to_location => #ebayTemplate.shipToLocation
)
]
),
:return_policy => Ebay::Types::ReturnPolicy.new (
:description => 'this product for suckers only!',
:returns_accepted_option => 'ReturnsAccepted'
)
#:condition_id => 1000
)
#response = #ebay.add_item(:item => item)
As you can see, it is just a mutation of the example given by Cody Fauser. The condition_id at the bottom will bring up an error as there is no such attribute. It seems to me there is no facility for this in the gem since the requirement came into existence after the gem was created. I have not been able to find any other gems to connect with ebay. I have also noticed, there are very little complaints about this even though people are still downloading the gem (10 people downloaded it today). I think there are quite a number of people writing for ebay. Is there a key word I am missing to specify the condition? A work around that people have been using? Another gem I have missed?
There is an existing item_conditions_codes.rb in the gem's type directory and only has two values New and Used. Guess you could add more values in there. However still needs mapping to ID's per the updating (and changed from Attributes) method
You have to modify in the gem library in .. ruby/1.8/gems/ebayapi-0.12.0/lib/ebay/types/item.rb
and add the following new lines
# added to allow ConditionID to be pushed into XML
numeric_node :condition_id, 'ConditionID', :optional => true
then in your ruby ebay code use the following convention
:condition_id => 1500,
At least that seems to work for me right now.

ruby gem flickr-fu license problem

I've trying to get the flickr-fu gem to search correctly only for commercial friendly photos but with no luck. It seems to ignore the parameter altogether.
photos = flickr.photos.search(:text => "anything",
:tags => 'architecture',
#:license_id => '4,6,5',
:license_id => [0,4,5,6],
#:license_id => 0,
:content_type => '1',
:safe_search => '1',
:sort => 'date-posted-asc, relevance',
:per_page => 5)
The license IDs 1,2,3 are NonCommercial, so I'm trying to avoid those and take all others, but it doesn't seem to matter, i'm still getting a lot of 3s in my query.
http://www.flickr.com/services/api/flickr.photos.licenses.getInfo.html
http://github.com/commonthread/flickr_fu/blob/master/lib/flickr/photos.rb
Nevermind, this seems to work.
photos = flickr.photos.search(:text => "anything",
:tags => 'architecture',
:license => '0,4,5,6',
:content_type => '1',
:safe_search => '1',
:sort => 'date-posted-asc, relevance',
:per_page => 5)

Resources