How to duplicate object "by value" in Rails? - ruby-on-rails

I need to duplicate a product in my spree application. So
def my_duplicate_product(product)
product.dup.tap do |new_product|
new_product.slug = "#{product.slug}-#{rand(1000)}"
...
This code causes the original product#slug to be changed.
What am I supposed to do to get a copy of that particular product and leave the original unchanged?
Rails version: 4.0.3
Update:
The problem is not in Ruby, nor Rails — it's all about globalize gem (v. 4.0.0).
This error was fixed in 4.0.3.
It realy broke #dup so some values were "shared" between the original model and the duplicated one.
See GitHub issue tracker for more information: https://github.com/globalize/globalize/pull/352

Maybe clone works:
def my_duplicate_product(product)
product.clone.tap do |new_product|
new_product.slug = "#{product.slug}-#{rand(1000)}"
Clone method on ruby doc

Update globalize gem to 4.0.3
See GitHub issue tracker for more information: https://github.com/globalize/globalize/pull/352

Related

Rails method global params kind_in error when upgraded

I've recently done an rails and ruby upgrade, we don't have strong params in the app (I know it's legacy).
So the way it's done in the app we have the following
def all_params_permitted(this_params = nil)
this_params = params if this_params == nil
this_params.permit!
this_params.each do |i, v|
if v.kind_in?([Hash, ActionController::Parameters])
all_params_permitted(v)
end
end
end
Which loops through all params and just accepts everything, all_params_permitted is called throughout the app I would love to add strong params but that's a no-go for now.
The issue in the above method is kind_in? the upgrade I did for this app was rails 5.0.3 to rails 6.1+ and went from ruby 2.2.6 to ruby 3.0.1 so I'm not sure why kind_in? has stopped working. This is an old app (built-in rails 2) so not sure if this has been deprecated.
Any help here would be great.
Edit
I have tried kind_of? but no dice.
the upgrade I did for this app was rails 5.0.3 to rails 6.1+ and went from ruby 2.2.6 to ruby 3.0.1
This is asking for trouble. It is strongly advised to try upgrading one minor version at a time (e.g. rails 5.0 --> 5.1 --> 5.2 --> 6.0 --> 6.1), otherwise you're very likely to break things with little information on why it's stopped working/how to fix it.
Likewise for ruby versions... At an absolute minimum I'd postpone the final upgrade to ruby v3 until your application works fine under ruby 2.7.
I'm not sure why kind_in? has stopped working
Nor am I, because that's a custom method. You haven't show us how it's defined, and nor have you shown us the error message, so it's impossible for me to say with confidence what's gone wrong.
My guess is that it's implemented something like this:
class Object
def kind_in?(classes)
classes.any? { |c| self.kind_of?(c) }
end
end
i.e. it's a little wrapper around the built-in kind_of? method.
And with that said, I still have no idea why this would have "stopped working" due to a ruby and/or rails upgrade.
Not sure about kind_in?, also didn't find any reference to that method, also as you have not posted the error so not sure about your issue. is_a?, kind_of?, instance_of? are few methods that check the object class but they check only a single class. Looking at your code one option for your condition could be:
if [Hash, ActionController::Parameters].include?(v.class)
which will check if it belongs to one of these classes.

Ruby API response as lower camel case

I'm trying to return the API response as lowerCamelCase but it is not working, I need to do this for all my Controllers/fields so I need a solution for entire project.
I've tried a lot of stuff, including this (http://brentvatne.ca/automatic-casing-activemodel-serializer/) who tells me to configure Activemodel to lower_camel as following
ActiveModel::Serializer.config.key_format = :lower_camel
But that is not working, it is returning the following json
{
"users": [{
"id": "56b110089c28691b84a3bd73",
"first_name": "Lucas"
}]
}
I need to transform the first_name into firstName.
Versions:
rails -v
Rails 4.2.5
ruby -v
ruby 2.2.3p173 (2015-08-18 revision 51636) [i386-mingw32]
And the gems
active_model_serializers (0.10.0.rc4)
rails-api (0.4.0)
My ember App recognize the JSON but I don't want to use snake case variables on JS
Boom! I found it! I had to dig through the AMS repo (and eventually stumbled upon a helpful readme) but here it is for v0.10:
ActiveModelSerializers.config.key_transform = :camel_lower
Put that in an initializer.
There are also other options: :dash, :camel, :underscore, and :unaltered, and nil
https://github.com/rails-api/active_model_serializers/blob/a032201a91cbca407211bca0392ba881eef1f7ba/docs/general/configuration_options.md
The problem was on the version of Active Model Serializer (0.10.0rc2).
On the last stable version (0.9) there was an issue that has been merged to fix the camelCase but this same PR is not present on the 0.10 RC versions.
So after I have downgraded the gem it worked :)
Search a project for key_format in case it's overridden somewhere.
Please try it in the console, try to set key_format explicitly to make sure it's possible (ex MySerializer.new(object, key_format: :lower_camel).as_json)
If it doesn't help you can put here code example how you are using serializers.

Rails model: saving works locally but not on Heroku

I have a Rails model for a Recipe.
It has an attribute, views, which counts how many times it has been viewed.
In the show action of my controller, I fetch the model object normally:
#recipe = Recipe.find(params[:id])
Then I increase the view count and save:
#recipe.views = #recipe.views + 1
#recipe.save
This works without a hitch locally, but on Heroku, the save apparently doesn't happen.
No errors are thrown.
I can run this exact same code in the rails console on Heroku, and then it works.
The only way I can get it to work, is setting
config.cache_classes = false
in environmenst/production.rb
This is obvously not what I want, but I'm stumped about how to go from here.
I'm running Rails 3.2.8, Ruby 1.9.3 on the Cedar stack, using Postgresql 9.1 in both development and on production.
FWIW to future searchers looking for their own solution, Benjamin Tan's answer (in comments) of heroku restart was what worked for me when I had a similar problem.
Copying the answer from the edited question body in order to remove this question from the "Unanswered" filter:
UPDATE: Fixed
Turns out I had a file with another older definition of the controller in the app/controllers directory.
~ answer per Azzar

rails generate migration : no more version number - acts_as_archive compatibility?

When I do a:
rails generate migration xxx
I get : ... create db/migrate/_xxx.rb
No timestamp and not any kind of numbering.
I tried:
rake db:migrate:reset -> no change
rake db:version -> correct value (20120509143011)
add config.active_record.timestamped_migration=false -> same problem (so i removed this line)
I'm using rails 3.2 - ruby 1.9.2 - rvm - mysql
Any idea?
Problem corrected ... but i'm not sure why ;-(
The last thing i did was to remove the gem "act_as_archive". then i generated a migration to remove the corresponding table and, my timestamp were back !
I did this 2 or 3 times (adding/removing the gem), and the problem is reproductible (in my project at least)
So I suppose this is a compatibility problem with acts_as_archive gem.
I hope this will help others.
The issue is the version of the 'also_migrate' gem that the acts_as_archive uses (0.35). The next version (0.36) fixes the problem. If memory serves I believe the method_missing alias was not returning a value from whatever operation it performed

Problems updating Paperclip from plugin to gem

I am apparently having a huge problem switching from the plugin version of Paperclip to the gem version in my app. It's been my impression that there should be no difference whatsoever between a plugin and a gem of a specified version. However, I'm not seeing this as an easy transition at all.
Rails 2.3.11, Ruby 1.8.7
The plugin version I am using is version 2.3.3 and was upgraded on August 2, 2010. Attempting to update this to the gem of the same version basically killed all my tests, not being able to load a factory model which did not have its attachment loaded. It appeared that validate_attachment_content_type was also attempting to validate the attachment presence, and couldn't find it, so everything just started breaking. Again, with the plugin there are no problems and I haven't had any problems in all this time we've been using it. On the other hand, this problem seems to not occur past version 2.3.4. That's a whole other set of problems.
Basically, in all versions from 2.3.4 and up I get the problem below:
can't convert nil into String
/home/joshua/.rvm/gems/ruby-1.8.7-p334#paperclip_upgrade/gems/paperclip-2.3.15/lib/paperclip/storage/s3.rb:163:in `extname'
/home/joshua/.rvm/gems/ruby-1.8.7-p334#paperclip_upgrade/gems/paperclip-2.3.15/lib/paperclip/storage/s3.rb:163:in `to_file'
/home/joshua/.rvm/gems/ruby-1.8.7-p334#paperclip_upgrade/gems/paperclip-2.3.15/lib/paperclip/attachment.rb:94:in `assign'
/home/joshua/.rvm/gems/ruby-1.8.7-p334#paperclip_upgrade/gems/paperclip-2.3.15/lib/paperclip.rb:279:in `avatar='
/home/joshua/railscamp/app/app/models/organization.rb:311:in `copy_membership'
in all my tests that access my organization model.
The apparent offending code in this case is attempting to clone a membership model from one organization to another, with the * line being the offending call.
def copy_membership(membership)
m = membership.clone
u = m.user.clone
u.organization = self
m.organization = self
begin
m.avatar = membership.avatar *
rescue RuntimeError
m.avatar = nil
end
m.user = u
m.save
m
end
Does this make any sense to anyone? Why would the plugin work, but the gem of the same version just wrecks everything?
Update: I also don't appear to have any paperclip rake tasks available. Any ideas?
As it turns out, we should have been checking whether the filename is valid or not, rather than depending on a generic runtime error for detecting avatar presence.

Resources