disable Rubocop complaint about method - ruby-on-rails

I have a method that goes like this return if amount == 0 and rubocop is complaining that it should be like return if amount.zero?. How can I have it skip over that method? Here is my .rubocop.yml:
rubocop
StringLiterals:
EnforcedStyle: double_quotes
Enabled: true
Style/FrozenStringLiteralComment:
Enabled: false
Style/TrailingCommaInLiteral:
Enabled: false
Style/TrailingCommaInArguments:
Enabled: false
Style/CaseEquality:
Enabled: false
Documentation:
Description: "Document classes and non-namespace modules."
Enabled: false
Metrics/MethodLength:
CountComments: false
Max: 15
Rails/Delegate:
Enabled: false
AllCops:
Exclude:
- db/**/*
- config/**/*
- script/**/*
- vendor/**/*
- bin/**/*
- Rakefile
- spec/spec_helper.rb
- spec/rails_helper.rb
- spec/teaspoon_env.rb
TargetRubyVersion: 2.3
Rails:
Enabled: true
submit_ticket_payment.rb
def call
return if amount == 0
Stripe::Charge.create(
amount: amount,
currency: "usd",
description: event_name,
receipt_email: context.rsvp.email,
source: context.token,
statement_descriptor: event_name
)
rescue Stripe::StripeError
context.fail!
end
So basically how can I have it not care about that particular instance?

The check in question is implemented by the Style/NumericPredicate cop.
If you generally want it to be enabled but not complain about an individual occurence, you can temporarily disable it with a special comment:
# rubocop:disable Style/NumericPredicate
return if amount == 0
# rubocop:enable Style/NumericPredicate
Note that it needs to be enabled again; otherwise it will skip the check for the whole remainder of the file.

If you wish to skip rule only for this particular method then:
# rubocop:disable Style/NumericPredicate
def call
return if amount == 0
# ...
end
# rubocop:enable Style/NumericPredicate

Related

Write RSpec for include method

Need to write RSpec for specific function:
def display_type(record,house_record)
#user_value = either user will provide input through enviroment, else it will be ['dctEng']
user_value =
if ENV['USER_VALUE'].nil?
ServiceConfig[:USER_VALUE]
else
ENV['USER_VALUE'].split(',')
end
user_value.map!(&:downcase)
myArr = [
'ani',
'awe',
'emi'
]
if user_value.include?(record[:mnemonic].downcase)
return (myArr.include?(house_record[:name] || house_record[:mnemonic]) ? true : false)
else
return [true, false].sample
end
end
I tried this one:
I have added the variable record and house_record but don't know how to properly write testcase for this method
describe '#display_type' do
let(:record) do
{
name: 'test_name',
mnemonic: 'test_schema_name1'
}
end
let(:house_record) do
{
name: 'test_name',
mnemonic: 'test_mnemonic',
row: true,
col: true
}
end
let(:user_value) do [
'test_name1',
'test_name2'
] end
let(:myArr) do [
'test1',
'test2',
'test3',
'test4'
] end
#updated_code:
it 'should include record[:mnemonic] in myArr array' do
result = display_type(record,house_record)
expect([true]).to include(result)
end
it 'should not include record[:mnemonic] in myArr array' do
result = display_type(record,house_record2)
expect([true,false]).to include(result)
end
end
But don't know how to complete it, getting continuous error:
It is not coming under IF block return statement, I tried to check it using binding.pry, it is giving true for
if user_value.include?(record[:mnemonic].downcase)
return (myArr.include?(house_record[:name] || house_record[:mnemonic]) ? true : false)
But while running rspec it is going to else block and do sampling based on true and false
Kindly, give a look, I updated one case, how to improve it, because it is not going in if condition

Swagger - How to write an example for a Free-Form Object?

We have a response type "Error" that may contain a field "extraInfo".
Error:
type: object
properties:
code:
type: string
message:
type: string
extraInfo:
description: any complementary information
type: object
// how to provide examples here?
One example for it can be :
"extraInfo": {
"doors": {
"frontLeftClosed": false,
"frontRightClosed": true,
"rearLeftClosed": true,
"rearRightClosed": true,
"trunkClosed": true
},
"windows": {
"frontLeftClosed": false,
"rearLeftClosed": true,
"trunkClosed": false
}
}
another could be :
"extraInfo": {
"transactionId": "77812783001"
}
Since it s a free form object, is there a way to provide examples for it in Swagger?
Couldn't find it in the spec : https://swagger.io/docs/specification/data-models/data-types/
Use the example keyword and specify the example value using the YAML or JSON object syntax:
extraInfo:
description: any complementary information
type: object
example: # <-------
doors:
frontLeftClosed: false
frontRightClosed: true
rearLeftClosed: true
rearRightClosed: true
trunkClosed: true
windows:
frontLeftClosed: false
rearLeftClosed: true
trunkClosed: false
OpenAPI 3.1 (which is compatible with JSON Schema 2020-12) also supports multiple examples for schemas and properties.
# openapi: 3.1.0
extraInfo:
description: any complementary information
type: object
# A list of examples
examples:
# Example 1
- transactionId: '77812783001'
# Example 2
- doors:
frontLeftClosed: false
frontRightClosed: true
rearLeftClosed: true
rearRightClosed: true
trunkClosed: true
windows:
frontLeftClosed: false
rearLeftClosed: true
trunkClosed: false

Rails logic not firing on `false` results

Receiving as an API an array of hashes
#request['clients'].each do |client|
validations are being executed on each clientattributes. However, rails logic is failing to fire up on false statements and this ignoring them. Example validation:
def client_type_ok
if #this_client['type'] == "ADT" || #this_client['type'] == "CHD"
true
else
false
#error_code_39 = true
end
end
The controller action wants to execute only when true conditions are met:
if client_type_ok && client_type_ok
However Rails.logger is clearly confirming that this condition is being passed through although false.
Rails.logger.info !#this_client['type'].blank?
Rails.logger.info #this_client['type']
Rails.logger.info "not"
Rails.logger.info #this_client['type'] != "ADT"
Rails.logger.info "ADT"
Rails.logger.info #this_client['type'] == "ADT"
is returning
true
APT
not
true
ADT
` `
The bottom is generated as a blank. The same occurs replacing Rails.logger with p. All logic of this action is ignoring false results. While I can attempt to devise processing cases of fully true cases, this is inconvenient and counter-intuitive.
Thus, there appears to be a meta function which is impeding the handling of false cases. How can this be tracked down? Can Rails.logger logic be step traced?
You're not returning false there
def client_type_ok
if #this_client['type'] == "ADT" || #this_client['type'] == "CHD"
true
else
false # this is not doing anything. Simply ignored.
#error_code_39 = true # result of this assignment will be true.
# and it also is the last expression of the if
# so it becomes the implicit return value of the method
end
end
def client_type_ok
if #this_client['type'] == "ADT" || #this_client['type'] == "CHD"
true
else
false
#error_code_39 = true
end
end
As Sergio mentiond in the above answer,The return value of yur method will be true for the else condtion. You need to swap the places or You can rewrite the above method
def client_type_ok
return true if %w(ADT CHD).include?(#this_client['type'])
#error_code_39 = true
false
end

How can hash.values.all? == false return true when all the values are not false?

How can #filters.values.all? == false return true when `#filters.values' clearly shows three true values?
EDIT: And how do you check to see if every value is false?
EDIT2: Because people want to copy and paste an arbitrary code snippet:
f = {
self: true,
clear: true,
something1: false,
something2: true
}
f.all? == false
==> false
f.values.all? == false
==> true
f.values
==> [true, true, false, true]
Enumerable#all?, from the docs:
Passes each element of the collection to the given block. The method
returns true if the block never returns false or nil. If the block is
not given, Ruby adds an implicit block of { |obj| obj } which will
cause all? to return true when none of the collection members are
false or nil.
That means that #filters.values.all? will return false unless every attribute is set to true (or truthy, to be more accurate) so, if you want to know when every item is false, then you will have to pass a block to all? and check each value, like this:
#filters.values.all? { |value| value == false } #=> true
UPDATE
Previous answer stated that also !#filters.values.all? will return true when all values are truthy, and that's true, but it will also return true if only one is set to false; in fact, it will always return true unless all values are set to true.
I guess the all? method will call the block with each
For eaxmple enumerable.all? will be executed like this:
enumerable.each {|x| x }
hash_enumerable.each {|k, _v| k }
So when the enumerable is a hash the block firt params will be the key....
To check if all the values in your hash is false, try this:
temp = {self: false, clear: false, lorem: false, ipsum: false}
temp.values.uniq == [false]
#=> true
temp2 = {self: true, clear: true, lorem: false, ipsum: true}
temp2.values.uniq == [false]
#=> false
A shorter, though slightly less clear, way to determine if all of the values are false is to simply ask if any of them are true and negate the response:
#filters = {foo: false, bar: true, baz: false}
!#filters.values.any? #=> false
#filters = {foo: false, bar: false, baz: false}
!#filters.values.any? #=> true

Switching between two boolean values in Ruby

I have the following code in a controller action, which looks at a user, and changes a boolean value to the opposite value, so if the user is true then it becomes false, and vice versa:
if current_user.enable_access
current_user.update_attribute(:enable_access, false)
else
current_user.update_attribute(:enable_access, true)
end
Is there a neater way of writing this?
How about using the toggle method that was specifically intended for this?
current_user.toggle(:enable_access)
If you want to add persistence in one character, there's also the toggle! method.
current_user.toggle!(:enable_access)
In one line, if current_user.enable_access can be only true`false`:
current_user.update_attribute(:enable_access, !current_user.enable_access)
Here's something to meditate on:
false # => false
true # => true
!false # => true
!true # => false
foo = false # => false
!foo # => true
foo = !foo # => true
foo = nil # => nil
!foo # => true
foo = !nil # => true
foo = !false # => true
Notice !!, which is a convenient way to turn a value into a true/false:
foo = !!nil # => false
foo = !!false # => false
foo = 1 # => 1
!foo # => false
!!foo # => true
foo = 'a' # => "a"
!foo # => false
!!foo # => true
0 == 1 # => false
1 == 1 # => true
'a' == '' # => false
'a' == 'a' # => true
These are the building blocks for comparisons in Ruby.
While the answer by #Зеленый is absolutely correct I wondered, that there is no DRY way to accomplish such a silly task.
The problem is that true and false in Ruby are instances of different classes, TrueClass and FalseClass respectively. That said, one can not just switch the boolean value inplace.
But what we can imagine, mediating at update_attribute source? Probably this is a shortest way to accomplish your task (please, do not use it at home, it’s a joke after all.)
current_user.tap do |cu|
cu.enable_access ^= true
end.save validate: false
I just reinvented toggle!, thanks #Dremni for pointing this out.
current_user.toggle!(:enable_access)
http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-toggle-21
I believe the DRY way to accomplish it would be to use:
current_user.enable_access = !current_user.enable_access
Then you could just write a method on a model and call it from any controller.
user.rb
def enable_user_access
self.enable_access = !self.enable_access
end
then calling it from a controller
current_user.enable_user_access

Resources