rails helper to give a upload file a unique name? - ruby-on-rails

Hey guys
I'm now working on a project that require upload a lot of videos, Does rails have this helper can handle this, like the address of youtube video :
www.youtube.com/watch?v=KYUhtPV_Lk4
Thanks

You can generate a random string like this and use it as the file name:
Digest::SHA1.hexdigest(Time.now.to_s) # => 800b262b59296b660a4f73e23580809143ed8846

are you using activerecord to model the files or are they simply flat files somewhere?
if you have a model like UploadedFile << ActiveRecord::Base for each file you can just use the id of the model or if you want a string you can hash it with some string added as salt.
irb(main):021:0> file_id = 1
=> 1
irb(main):022:0> Digest::SHA1.hexdigest('SomeRandomString' + file_id.to_s)
=> "70f5eedc8d4f02fd8f5d4e09ca8925c2f8d6b942"
if you are simply keeping them as flat files on the system, you can hash their path+filename to create a unique string.
irb(main):016:0> Digest::SHA1.hexdigest '/home/bob/somefile.mp4'
=> "204a038eddff90637c529af7003e77d600428271"
and you can always add in a timestamp of the current time and a random number to prevent dupes.

SecureRandom.uuid generates a v4 random UUID (Universally Unique IDentifier)
It doesn't contain meaningful
information such as MAC address, time, etc.
See RFC 4122 for
details of UUID.
SecureRandom::uuid

Related

How to create a hash for all records created by a user?

In our Rails app, the user (or we on his behalf) load some data or even insert it manually using a crud.
After this step the user must validate all the configuration (the data) and "accept and agree" that it's all correct.
On a given day, the application will execute some tasks according the configuration.
Today, we already have a "freeze" flag, where we can prevent changes in the data, so the user cannot mess the things up...
But we also would like to do something like hash the data and say something like "your config is frozen and the hash is 34FE00...".
This would give the user a certain that the system is running with the configuration he approved.
How can we do that? There are 7 or 8 tables. The total of records created would be around 2k or 3k.
How to hash the data to detect changes after the approval? How would you do that?
I'm thinking about doing a find_by_user in each table, loop all records and use some fields (or all) to build a string and hash it at the end of the current loop.
After loop all tables, I would have 8 hash strings and would concatenate and hash them in a final hash.
How does it looks like? Any ideas?
Here's a possible implementation. Just define object as an Array of all the stuff you'd like to hash :
require 'digest/md5'
def validation_hash(object, len = 16)
Digest::MD5.hexdigest(object.to_json)[0,len]
end
puts validation_hash([Actor.first,Movie.first(5)])
# => 94eba93c0a8e92f8
# After changing a single character in the first Actors's biography :
# => 35f342d915d6be4e

How to search for a record and then delete it

How to search for the ttoken record by mobile no. and then delete that record?
User.rb:
field :ttokens, type: Hash, :default => {} # Stored as hash over numbers
Normally the value of ttokens, in the rails console, are as follows:
ttokens: {"919839398393"=>{"atoken"=>"f704e803061e594150b09ad8akabfc6105ac85ab", "confirmed"=>true}, "91812798765"=>{"atoken"=>"255cb70926978b93eik67edb52fa23a163587b4b", "confirmed"=>true}}
I need a mongodb query to search for the ttoken record by mobile number and then delete that record. The DB used is MongoDB. Any guidance or help would be highly appreciated.
You need to use MongoDB 'dot notation' for the embedded element, which means the "key" must be a string type of notation. Also apply $exists to match where the key in the has is present and the .unset() method from mongoid:
User.where('_id'=> userId, 'ttokens.919839398393'=> { '$exists' => true }).unset(
'ttokens.919839398393'
)
This is effectively the $unset operator of MongoDB, which removes "keys" from the document by the path specified.
From the sample document this would match and remove the first key, leaving only the other.

how can I seed the ID number into my data when using Rails?

I am importing some data from an old Omnis 7 databse via a text file into Rails. I am using text files for this purpose and am using db:seed to port it in.
In my seeds.rb file I have:
Port.delete_all
File.open("db_ports.txt", "r") do |ports|
ports.read.each_line do |port|
id, name, un_locode, bunker_surcharge, launch_tariff = port.chomp.split("|")
Port.create!(:id => id, :name => name, :un_locode => un_locode, :bunker_surcharge => bunker_surcharge, :launch_tariff => launch_tariff)
end
end
I would like to have the ID number be the one as was assigned in the other database because Berths have a foreign key that looks to Ports and I would need those to match up with each other.
However, when I last imported my data, this didn't work out as planned and the ID number was not passed in. I'm guessing that I could create empty records which I would then update with the data but was wondering whether this was possible.
You won't be able to set the id in the create! call because id is protected from mass assignment in this way. I believe you can set the id by doing something like:
port = Port.new(:name => name, :un_locode => un_locode, ... )
port.id = id
port.save!
You might want to consider having a separate attribute for the id in the old system though (old_omnis_id, maybe). I've seen this work successfully in the past. You can then use this attribute to join on in the association or, when you add the berths, you can look up the port's id in the new system by the old id.

rails read the file and store the database

i saved .rb file in app/component/text.rb. i want to read and store the database.
in that file has 5 rows and my table also have 5 rows.i want to save line by line.you can understand my question.i use mysql database.
please help me....
thanks,
kingston.s
I missed the rails- and ruby-version, the operating system you use and a clear problem description...anyway
Assuming that you meant your database would have 5 fields and you want to read and write a record to a file:
Assuming the file will contain a record for the model "Apple "with the fields id, title and description.
Read new Apple from file:
indexes = [:id, :title, :desc].reverse # be careful the data will be saved reverse because pop takes the last element first
record_params = {}
handle = File.open("Apple.record","r")
handle.lines.each do |line|
record_params[indexes.pop]=line.chomp #use chomp to get rid of the trailing \n
end
handle.close
Apple.create!(record_params)
Write Apple with id 7 to a File
indexes = [:id, :title, :desc]
record = Apple.find(7)
to_save = indexes.map{|i| record.send i}
handle = File.open("Apple.record","w")
handle.write(to_save.join("\n"))
handle.close
Beware to escape the linebreaks in your data if there are any possible..
Anyway it would be much easier to use YAML:
#write the first apple to the file
handle = File.open("Apple.record", "w")
handle = Apple.first.to_yaml
handle.close
#read the file to a new record
record_params = YAML.load File.read("Apple.record")
Apple.create!(record_params)
All this worked in Rails 3, but remember, that you are saving the id as well, therefore saving and loading will cause the id to change, because a record with the given id already existed.

Getting Mongoid from params array

In order to find a Root Document that contains a embedded document using MongoID/Rails 3 I need to do my query this way:
QuoteRequest.where( "order_request_items._id" => BSON::ObjectID(params[:id]) ).first
Is there a way to query without using the BSON::ObjectID ?
Thanks!
I'm not a MongoID/Rails user, but my guess is that you can't.
Even in the Mongo shell you have to use ObjectId() if you want to compare ObjectIDs. Something like this won't return any results:
db.foo.find({_id: "4c7ca651db48000000002277"})
You'll have to create an actual ObjectID from the string in order to get results:
db.foo.find({_id: ObjectId("4c7ca651db48000000002277")})
MongoID apparently doesn't automatically convert your input to ObjectIDs. But perhaps there's a way to tell MongoID which fields it should always convert to ObjectIDs? Then you would be able to omit the use of BSON::ObjectID.
This is a bug, the ids should be automagically converted by Mongoid. You should open a ticket on github: http://github.com/mongoid/mongoid/issues

Resources