I wrote a lib/animal.rb with several lists of params, and I want to reference that list in my controller and add it my params list. I did this because I use this list in several locations and didn't want to litter my code with a bunch of references to the library.
Controller
ANIMAL_TYPE_INPUT_PARAMS = *Animals::ANIMAL_TYPE_PARAMS.freeze
....
def familar_params
params.permit(ANIMAL_TYPE_INPUT_PARAMS, OTHER_PARAM_LIST....)
end
Lib/animal.rb
module Animal
# param lists
ANIMAL_TYPE_PARAMS = [
:animal_has_fur, :animal_id, :animal_weight
].freeze
end
Functionally it works just fine, but I am seeing a weird rubocop error. I would prefer to not disable MutableConstant for this section (disabling rubocop is usually a band aid that you pay for at some point).
Rubocop error
app/controllers/api/v1/example_controller.rb:55:24: C: Freeze mutable objects assigned to constants.
ANIMAL_TYPE_INPUT_PARAMS = *Animals::ANIMAL_TYPE_PARAMS.freeze
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I looked into this question: Ruby rubocop: how to freeze an array constant generated with splat But mine are already arrays, so I feel like it doesn't apply to me / shouldn't have to call to_a.
As #drenmi suggested, it was an older version of rubocop giving me this error. Once I upgraded to 0.46.0 the error was no longer.
Related
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
My project uses HoundCI as a code linter, which I believe internally uses rubocop.
Recently I started noticing this sort of warning -
It appears on every class definition (e.g. class User < ActiveRecord::Base).
I understand the concept of freezing string literals, but why would it expect me to freeze class definitions? Also more importantly, how do I disable it? It's quite annoying to have 10+ of these "errors" polluting our pull requests.
Thank you!
Edit: Looks like it also started appearing on require statements that use string literals, like with rspec tests. This is definitely new and wasn't being flagged previously
It looks like Hound/Rubocop is detecting a violation of the FrozenStringLiteralComment cop.
This cop is designed to help upgrade to Ruby 3.0. It will add the comment # frozen_string_literal: true to the top of files to enable frozen string literals. Frozen string literals will be default in Ruby 3.0. The comment will be added below a shebang and encoding comment. The frozen string literal comment is only valid in Ruby 2.3+.
You can either add the magic comment manually to the top of your files
# frozen_string_literal: true
Or have Rubocop do it for you
$ bundle exec rubocop --auto-correct --only FrozenStringLiteralComment
You can also ignore the cop in your rubocop.yml, Style/FrozenStringLiteralComment
I primarily work in Rails and I'm using a command line data conversion gem, "Mongify" and I am stumped about how to extend core classes in a Ruby cli app.
I want to extend the String class with an .is_date? method to check whether a string can be converted to a Date. I've got it working in the Rails Console,
I added a string.rb file to lib/ext with the following;
class String
def is_date?
begin
return true if Date.parse(self)
rescue
#do nothing
end
return false
end
end
Then in a Rails console I do a require 'ext/string' and it will work.
But I can't figure out how to get it to work in the Mongify cli app. I copied string.rb into the lib folder of the gem and I've tried adding require 'string' to a number of different files in the gem, but I keep getting undefined method errors.
Can someone point me in the right direction?
How about you require it from lib/mongify.rb like so:
require 'string/extensions.rb'
And then put your code in lib/string/extensions.rb
Let us know the exact undefined method errors you're getting in case this isn't the solution.
To help you with the debugging exercise that would give you the answer you need. Start by putting a breakpoint right before the place of the function call.
In the debugger, load the required document and then step past your breakpoint to the next one after the call has occurred.
Once you have this working, then start earlier in the stack trace – in a file that loaded before that one. Keep moving backwards until you get to a sufficiently early part in the load process of the gem, and make that be the place you load your code.
I don't know why these two pieces of code behave different in Ruby 1.8.7 since one seems to be the single line version of the other.
The first piece of code (it works as it should):
if #type.present?
type = #type
orders = Order.where{type.eq(type)}
end
The single line version (it doesn't work at all, no error but seems no execution too):
orders = Order.where{type.eq(type)} if (type = #type).present?
NOTE: I'm using the squeel gem, that is the reason a block follows the where method. Also the variable type has to capture the instance variable #type since the execution context changes inside the block and the instance variables are not shared between the main context and the block context.
NOTE 2: I have to use Ruby 1.8.7 for legacy reasons.
Any idea? Thank you!
There is a problem with the order of parsing of your code. Variables need to be defined before they are used.
Even though variables defined inside if statement clauses "leak" out into the current scope, they do not leak "backwards" in Ruby code.
Ruby is a little bit curious in that way that variables need to be defined before the parser parses the code. The parsing is done from top to bottom and left to right.
Hence since the variable type is defined after your block code where you use it, it will not be available in the block.
Example:
>> 3.times { puts x } if (x = 123)
NameError: undefined local variable or method `x' for main:Object
The reason you don't get any error message is that in Ruby 1.8 type is a method that is a synonym for Object#class.
So what your code is really doing is (probably):
orders = Order.where{type.eq(this.class)} if (type = #type).present?
To fix it you have to define type before you use it. Therefore you can't really turn that into a one-liner unless you simply do this instead:
orders = Order.where{type.eq(#type)} if #type.present?
All in all it's not a good idea in Ruby 1.8 to use type as a variable in Rails models, because of the Object#class issue it will most likely bring you headaches in the long run.
similar problem that i got was that 'type' is a keyword in database, it allows for our model to have the field as 'type' but it works strangely in different conditions. if changing the name is an option for you then check after changing it, worked for me...
gem Squeel uses instance_eval method when calls block which passed to where. So, there is no any #type in squeel instance. If you want to use methods or variables from another context, try to wrap it into method my with block
orders = Order.where { type.eq my { #type } } if #type.present?
PS sorry for my English
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?