This doesn't actually work. The version doesn't get processed but versions[:thumb] still exists.
Looking at the code, the :if option is only referenced in version_exists?. Which means that versions[:thumb] returns a version but version_exists?(:thumb) returns false.
It doesn't make sense to me but that's how it appears to work.
Related
I've got an application that's been running in production for many months now, with tens of thousands of attachments. This morning, I tried to do an operation on one of these attachments, and got the following error:
Azure::Core::Http::HTTPError: BlobNotFound (404): The specified blob does not exist.
I can easily recreate this blob, but this situation makes me want to write a script to check the integrity of all of my attachments, and verify that no others have gone missing. (I expect that this was a transitory network error, and I expect to find very few, but I need the peace of mind.)
I can see that there is a method to call that seems to do exactly what I need: exist?(key), which is documented here:
https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/service/disk_service.rb
However, I can't figure out how I'm supposed to call it. According to this, it's implemented as an instance method. So how do I reference my Rails application's active ActiveStorage instance (depending on environment) to use this method?
I wondered if it were possible to backtrack to get the instance of ActiveStorage::Service::AzureStorageService (in production), and found this answer on finding each instance of a class.
From there, I found that I could:
asass = ObjectSpace.each_object(ActiveStorage::Service::AzureStorageService).first
Which then allowed me to:
2.5.5 :015 > asass.exist?(c.json.blob.key)
AzureStorage Storage (313.3ms) Checked if file exists at key: ....PTLWNbEFLgeB8Y5x.... (yes)
=> true
Further digging around in the bowels of Rails' GitHub issues led me to see that the reference to the ActiveStorage service instance can be reached through an instance of a stored object, and that I could always be using the send() method to call one of its methods:
2.5.5 :045 > c.json.blob.service.send(:exist?, c.json.blob.key)
AzureStorage Storage (372.4ms) Checked if file exists at key: ....PTLWNbEFLgeB8Y5x.... (yes)
=> true
I'm sure both approaches are lighting up the same code paths, but I'm not sure which one I prefer at the moment. I still think there must exist some way to traverse the Rails instance through app. or Rails.application. to get to the ActiveStorage instance, but I haven't been able to suss that out.
I have been chasing an issue down for a while now, and still cannot figure out what's happening. I am unable to edit documents made from my gem through normal persistence methods, like update or even just editing attributes and calling save.
For example, calling:
Scram::Policy.where(id: a.id).first.update!(priority: 12345)
Will not work at all (there are no errors, but the document has not updated). But the following will work fine:
Scram::Policy.collection.find( { "_id" => a.id } ).update_one( { "$set" => {"priority" => 12345}})
I am not sure what I'm doing wrong. Calling update and save on any other model works fine. The document in question is from my gem: https://github.com/skreem/scram/blob/master/lib/scram/app/models/policy.rb
I cannot edit its embedded documents either (targets). I have tried removing the store_in macro, and specifying exactly what class to use using inverse_of and class_name in a fake app to reimplement these classes: https://github.com/skreem/scram-implementation/blob/master/lib/scram/lib/scram/app/models/policy.rb
I've tried reimplementing the entire gem into a clean fake rails application: https://github.com/skreem/scram-implementation
Running these in rails console demonstrates how updating does not work:
https://gist.github.com/skreem/c70f9ddcc269e78015dd31c92917fafa
Is this an issue with mongoid concerning embedded documents, or is there some small intricacy I am missing in my code?
EDIT:
The issue continues if you run irb from the root of my gem (scram) and then run the following:
require "scram.rb"
Mongoid.load!('./spec/config/mongoid.yml', :test)
Scram::Policy.first.update!(priority: 32) #=> doesn't update the document at all
Scram::Policy.where(id: "58af256f366a3536f0d54a61").update(priority: 322) #=> works just fine
Oddly enough, the following doesn't work:
Scram::Policy.where(id: "58af256f366a3536f0d54a61").first.update(priority: 322)
It seems like first isn't retrieving what I want. Doing an equality comparison shows that the first document is equal to the first returned by the where query.
Well. As it turns out, you cannot call a field collection_name or else mongoid will ensure bad things happen to you. Just renaming the field solved all my issues. Here's the code within mongoid that was responsible for the collision: https://github.com/mongodb/mongoid/blob/master/lib/mongoid/persistence_context.rb#L82
Here's the commit within my gem that fixed my issue: https://github.com/skreem/scram/commit/25995e955c235b24ac86d389dca59996fc60d822
Edit:
Make sure to update your Mongoid version if you have dealt with this issue and did not get any warnings! After creating an issue on the mongoid issue tracker, PersistenceContext was added to a list of prohibited methods. Now, attempting to use collection_name or collection as a field will cause mongoid to spit out a couple of warnings.
Fix commit: https://github.com/mongodb/mongoid/commit/6831518193321d2cb1642512432a19ec91f4b56d
Looks like it's a known issue but i'm not able to find any solution nor any dirty fix to make it working. The thing is i'm not able to remove attachments uploaded using Carrierwave plugin.
I'm using a special form field called :remove_avatar which should remove a avatar file and clear avatar column but the only thing it does is deleting the file, the file reference in avatar column still exists.
I was trying to remove it in any possible way but without a luck.
update_attributes
using u.update_attributes( :avatar => "" ) is not removing the reference
save()
u = User.find(int)
u.avatar = ""
u.save
is also not removing the reference
remove_avatar = true
u.remove_avatar = true
u.save
not working
remove_avatar!
u.remove_avatar!
u.save
not working
f.check_box :remove_avatar
not working
By 'not working' i mean that the file is removed from filesystem but the reference persists.
Cany you please provide me ANY tip i can use to make it working again? It can be something dirty, this bug shown a day before my deadline and i feel quite desperate. Thanks in advance.
Ruby: 1.8.7
Rails: 3.2.6
Carrierwave: master branch from git repo
According to this thread, you can probably manage this by using update_column instead of update_attribute, and then (for reasons not currently clear to me), really forcing a reload of the in-memory object (instead of just calling reload on it):
u = User.where('avatar is not null').last # Get a user with an avatar
u.update_column(:avatar, nil) # Use update_column to avoid callbacks
u = User.where(:id => u).first # Force a reload of the object. No, u.reload doesn't work. No, I don't know why.
When I do this in my console, u.avatar is finally blank.
My version info, in case this doesn't work for you: Ruby 1.9.3, Rails 3.2.2, PostgreSQL 9.2, CarrierWave 0.5.7
I want to check when attributes on a model have changed. I have attempted to check values != the value on the form before doing a save but that code is really ugly and is not working well at times. Same with using update_column which does not do the validations in my model class. If I use update_attributes without doing something else I will not be able to check when a field has been updated from my understanding. From my web research on Stack Overflow and other sites it appears that using ActiveModel Dirty is the way to go.
I have looked at this: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
My hope is to use this to check if boolean flags changed on a model after using update_attributes. I attempted to do the minimum implementation as described in the included link. I added the following to my ActiveRecord class:
include ActiveModel::Dirty
define_attribute_methods [:admin]
I tried adding the three attributes I wanted to keep track of. I started with just one attribute to see if I could get it working. I received the following error when I ran an rspec test. Once I removed the argument I had no errors.
Exception encountered: #<ArgumentError: wrong number of arguments (1 for 0)>
After I removed the argument I decided to include similar methods in my model using admin instead of name. Other Rspec tests broke on the save method. However I feel the problem is with how I am implementing ActiveModel Dirty.
I have read on other Stack Overflow posts where commenters stated that this was included in 3.2.8 so I upgraded from 3.2.6 to 3.2.8. I did not understand what that meant so after getting errors I decide just to leave the include ActiveModel::Dirty statement and try to use admin_changed? Of course it did not work.
I have not been able to find anything about how to initially set things up for this other than the link I included here. All the other research I have found assumes that the initial setup was correct and that updating to the current stable version of Rails would take care of their problems.
Any help would be appreciated on how to implement this. Doing the minimal implementation as stated in the link is not working. Maybe there is something else I am missing.
The problem appears to be that ActiveRecord redefines the define_attribute_methods method to accept 0 arguments (because ActiveRecord automatically creates attribute methods for every column in the database table): https://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_methods.rb#L23
This overrides the define_attribute_methods method provided by ActiveModel: https://github.com/rails/rails/blob/master/activemodel/lib/active_model/attribute_methods.rb#L240
Solution:
I figured out a solution that worked for me...
Save this file as lib/active_record/nonpersisted_attribute_methods.rb: https://gist.github.com/4600209
Then you can do something like this:
require 'active_record/nonpersisted_attribute_methods'
class Foo < ActiveRecord::Base
include ActiveRecord::NonPersistedAttributeMethods
define_nonpersisted_attribute_methods [:bar]
end
foo = Foo.new
foo.bar = 3
foo.bar_changed? # => true
foo.bar_was # => nil
foo.bar_change # => [nil, 3]
foo.changes[:bar] # => [nil, 3]
However, it looks like we get a warning when we do it this way:
DEPRECATION WARNING: You're trying to create an attribute `bar'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc.
So I don't know if this approach will break or be harder in Rails 4...
See also:
Track dirty for not-persisted attribute in an ActiveRecord object in rails
https://github.com/adzap/validates_timeliness/issues/73
Try adding adding =, like this:
define_attribute_methods = [:admin]
That change worked for me. Not sure if it has something to do with this?
In my current Rails 3 app, I'm doing some unit testing to make sure that calls to update S3 are only done under certain situations. I don't want to update S3 during tests, so I'm using Mocha to stub out the behaviour. Is there a way to make sure a function is called using mocha? I've taken a look at Expectations, and unless I'm doing it wrong, it seems I have to do:
object.expects(:function_name).once
However, this does not yield the desired results: This will flag an error if function_name is called twice(which is desired), it will NOT flag an error if it is only called once(as it should), but the problem is it WILL NOT flag an error if the function is called zero times. I need a way to make sure it is called. It seems like mocha should support this, so maybe I'm doing it wrong. Any help would be greatly appreciated.
***** CORRECTION:
Turns out that I was doing it right, except that the mocha_verify method wasn't being called automatically. For anyone who is having a similar problem, check out Ole Morten Amundsen's answer over here: Mocha Mock Carries To Another Test
or just
object.expects(:function_name).twice
alternatively, if it has differnet input you should test that
resultmock = mock
object.expects(:function_name).with(someobject).returns(mock)
resultmock.expects(:something).returns(true)
object.expects(:function_name).with(resultmock)
don't know if this helps, but it should give you a kick start. FYI: 'once' is default. Good luck, do TDD (=test-first) or mocking will be a pain :)
Be sure to load mocha last, so it is really being loaded, as in my answer here:
Mocha Mock Carries To Another Test
Try:
object.expects(:function_name).at_least_once
Have a look at the docs: http://mocha.rubyforge.org/classes/Mocha/Expectation.html#M000042