Rubocop not ignoring db/schema.rb file - rubocop

Why is my db/schema.rb file not being ignored by rubocop?
.rubocop.yml
require: rubocop-rails
require: rubocop-performance
AllCops:
Exclude:
- 'db/**/*'
- 'config/**/*'
- 'script/**/*'
- 'bin/{rails,rake}'
- 'vendor/**/*'
- 'spec/fixtures/**/*'
- 'tmp/**/*'
- 'Gemfile.lock'
Rails:
Enabled: true
# Commonly used screens these days easily fit more than 80 characters.
Metrics/LineLength:
Max: 120
# Too short methods lead to extraction of single-use methods, which can make
# the code easier to read (by naming things), but can also clutter the class
Metrics/MethodLength:
Max: 20
Metrics/BlockLength:
ExcludedMethods: ['describe', 'context', 'FactoryBot.define']
# The guiding principle of classes is SRP, SRP can't be accurately measured by LoC
Metrics/ClassLength:
Max: 1500
# No space makes the method definition shorter and differentiates
# from a regular assignment.
Layout/SpaceAroundEqualsInParameterDefault:
EnforcedStyle: no_space
Naming/VariableNumber:
EnforcedStyle: normalcase
# Single quotes being faster is hardly measurable and only affects parse time.
# Enforcing double quotes reduces the times where you need to change them
# when introducing an interpolation. Use single quotes only if their semantics
# are needed.
Style/StringLiterals:
EnforcedStyle: double_quotes
# We do not need to support Ruby 1.9, so this is good to use.
Style/SymbolArray:
Enabled: true
# Most readable form.
Layout/AlignHash:
EnforcedHashRocketStyle: table
EnforcedColonStyle: table
# Mixing the styles looks just silly.
Style/HashSyntax:
EnforcedStyle: ruby19_no_mixed_keys
# has_key? and has_value? are far more readable than key? and value?
Style/PreferredHashMethods:
Enabled: false
# String#% is by far the least verbose and only object oriented variant.
Style/FormatString:
EnforcedStyle: percent
Style/CollectionMethods:
Enabled: true
PreferredMethods:
# inject seems more common in the community.
reduce: "inject"
# Either allow this style or don't. Marking it as safe with parenthesis
# is silly. Let's try to live without them for now.
Style/ParenthesesAroundCondition:
AllowSafeAssignment: false
Lint/AssignmentInCondition:
AllowSafeAssignment: false
# A specialized exception class will take one or more arguments and construct the message from it.
# So both variants make sense.
Style/RaiseArgs:
Enabled: false
# Indenting the chained dots beneath each other is not supported by this cop,
# see https://github.com/bbatsov/rubocop/issues/1633
Layout/MultilineOperationIndentation:
Enabled: false
# Fail is an alias of raise. Avoid aliases, it's more cognitive load for no gain.
# The argument that fail should be used to abort the program is wrong too,
# there's Kernel#abort for that.
Style/SignalException:
EnforcedStyle: only_raise
# Suppressing exceptions can be perfectly fine, and be it to avoid to
# explicitly type nil into the rescue since that's what you want to return,
# or suppressing LoadError for optional dependencies
Lint/HandleExceptions:
Enabled: false
Layout/SpaceInsideBlockBraces:
# The space here provides no real gain in readability while consuming
# horizontal space that could be used for a better parameter name.
# Also {| differentiates better from a hash than { | does.
SpaceBeforeBlockParameters: false
# No trailing space differentiates better from the block:
# foo} means hash, foo } means block.
Layout/SpaceInsideHashLiteralBraces:
EnforcedStyle: no_space
# { ... } for multi-line blocks is okay, follow Weirichs rule instead:
# https://web.archive.org/web/20140221124509/http://onestepback.org/index.cgi/Tech/Ruby/BraceVsDoEnd.rdoc
Style/BlockDelimiters:
Enabled: false
# do / end blocks should be used for side effects,
# methods that run a block for side effects and have
# a useful return value are rare, assign the return
# value to a local variable for those cases.
Style/MethodCalledOnDoEndBlock:
Enabled: true
# Enforcing the names of variables? To single letter ones? Just no.
Style/SingleLineBlockParams:
Enabled: false
# Shadowing outer local variables with block parameters is often useful
# to not reinvent a new name for the same thing, it highlights the relation
# between the outer variable and the parameter. The cases where it's actually
# confusing are rare, and usually bad for other reasons already, for example
# because the method is too long.
Lint/ShadowingOuterLocalVariable:
Enabled: false
# Check with yard instead.
Style/Documentation:
Enabled: false
# This is just silly. Calling the argument `other` in all cases makes no sense.
Naming/BinaryOperatorParameterName:
Enabled: false
# There are valid cases, for example debugging Cucumber steps,
# also they'll fail CI anyway
Lint/Debugger:
Enabled: false
# Style preference
Style/MethodDefParentheses:
Enabled: false

I know this is an old question, but in case anybody's still having a similar issue:
When specifying multiple extensions such as rubocop-rails and rubocop-performance, provide them as an array to the require: directive, e.g.:
require:
- rubocop-rails
- rubocop-performance
Also worth noting is that rubocop-rails now ignores db/schema.rb by default (since version 2.4.1).

In my case I added only
AllCops:
Excludes:
- config/unicorn.rb
- db/**
Style/Documentation:
...
and rubocop is worked

In case anyone has the same confusion.. In my case, this was not actually a Rubocop issue. Running rails db:migrate was causing schema to be recreated and the column positions adjusted.

Related

Rails Engines with multiple databases

I am creating application in Ruby on Rails which is having many engines(for modularity).
I want different databases for each engine. How to configure this?
Database - MYSQL
There is a good explanation by the link http://www.blrice.net/blog/2016/04/09/one-rails-app-with-many-databases/
General approach is to take a look at the framework sources and decide can it be reused.
Let's take a look at activerecord/lib/active_record/railties/databases.rake (v5.0.7) first. For example on how db:create implemented.
We will see ActiveRecord::Tasks::DatabaseTasks.create_current.
Let's open ActiveRecord::Tasks::DatabaseTasks and take a look at
# The possible config values are:
#
# * +env+: current environment (like Rails.env).
# * +database_configuration+: configuration of your databases (as in +config/database.yml+).
# * +db_dir+: your +db+ directory.
# * +fixtures_path+: a path to fixtures directory.
# * +migrations_paths+: a list of paths to directories with migrations.
# * +seed_loader+: an object which will load seeds, it needs to respond to the +load_seed+ method.
# * +root+: a path to the root of the application.
#
# Example usage of DatabaseTasks outside Rails could look as such:
#
# include ActiveRecord::Tasks
# DatabaseTasks.database_configuration = YAML.load_file('my_database_config.yml')
# DatabaseTasks.db_dir = 'db'
# # other settings...
This way we are getting to following solution:
namespace :your_engine do
namespace :db do
task :load_config do
ActiveRecord::Tasks::DatabaseTasks.database_configuration = YAML.load_file("config/database_your_engine.yml")
ActiveRecord::Tasks::DatabaseTasks.db_dir = "db_your_engine"
ActiveRecord::Tasks::DatabaseTasks.migrations_paths = [ "components/your_engine/db/migrate" ]
ActiveRecord::Base.configurations = ActiveRecord::Tasks::DatabaseTasks.database_configuration
ActiveRecord::Migrator.migrations_paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths
# You can observe following values to see how settings applied.
# puts ActiveRecord::Base.configurations
# puts ActiveRecord::Migrator.migrations_paths
# puts ActiveRecord::Tasks::DatabaseTasks.database_configuration
# puts ActiveRecord::Tasks::DatabaseTasks.migrations_paths
end
desc "Create Your DB"
task create: :load_config do
ActiveRecord::Tasks::DatabaseTasks.create_current
end
end
end
The same approach for drop/migrate and other needed tasks.
It is good general rule - know you stack at least one level lower than your work with. Sometimes reading underlying sources much more helpful than direct answer.
I will update this answer while going forward with my solution...

Rubocop: how can I exclude a filename pattern from a metric?

I want to disable line length checking globally for filenames matching *_spec.rb (Serverspec files) in Rubocop.
I tried adding Exclude to config/default.yml in the following way, but it did not work (no error, offenses detected):
Metrics/LineLength:
Max: 80
AllowHeredoc: true
AllowURI: true
URISchemes:
- http
- https
Exclude:
- '*_spec.rb'
If it is possible, where/how should this be configured?
You can match files based on a regular expression by using the !ruby/regexp declaration:
Metrics/LineLength:
Max: 80
AllowHeredoc: true
AllowURI: true
URISchemes:
- http
- https
Exclude:
- !ruby/regexp /_spec\.rb$/
RuboCop recently added a new manual, and you can read about including and excluding files here.

Sublime build exec command array

I am confused as to why Sublime Text 2 build systems tend to put the exec command as an array. Though this is suggested in the docs (and works), just putting the command as a string works just as well, and is (in my opinion) more straightforward.
The Sublime Text build system uses subprocess.Popen, which recommends the usage of an array. Otherwise the interpretation is platform-dependent.
Cited from the python 2 subprocess documentation:
args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent (...). Unless otherwise stated, it is recommended to pass args as a sequence.
Additional important cite (thanks #Dimpl for pointing that out):
The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.
The shell argument is set True if you use the shell_cmd and False for cmd. Hence based on the cites I would suggest to use an array for cmd and a string for shell_cmd.

Parse ipv6 address in tcl

In TCL, I need to split an ipv6 address and port combination in the format [fec1::10]:80 to fec1::10 and 80.
Please suggest a way to do it.
Thanks!
(In the examples below I assume that the address will be subjected to further processing (expansion, etc) because there are a lot of forms that it can take: hence, in this preliminary stage I treat it simply as a string of any character rather than groups of hex digits separated by colons. The ip package mentioned by kostix is excellent for processing the address, just not for separating the address from the port number.)
Given the variable
set addrport {[fec1::10]:80}
There are several possible ways, including brute-force regular expression matching:
regexp -- {\[(.+)\]:(\d+)} $addrport -> addr port
(which means "capture a non-empty sequence of any character that is inside literal brackets, then skip a colon and thereafter capture a non-empty sequence of any digit"; the three variables at the end of the invocation get the whole match, the first captured submatch, and the second captured submatch, respectively)
(note 1: American usage of the word 'brackets' here: for British speakers I mean square brackets, not round brackets/parentheses)
(note 2: I'm using the code fragment -> in two ways: as a variable name in the above example, and as a commenting symbol denoting return value in some of the following examples. I hope you're not confused by it. Both usages are kind of a convention and are seen a lot in Tcl examples.)
regexp -inline -- {\[(.+)\]:(\d+)} $addrport
# -> {[fec1::10]:80} fec1::10 80
will instead give you a list with three elements (again, the whole match, the address, and the port).
Many programmers will stop looking for possible solutions here, but you're still with me, aren't you? Because there are more, possibly better, methods.
Another alternative is to convert the string to a two-element list (where the first element is the address and the second the port number):
split [string map {[ {} ]: { }} $addrport]
# -> fec1::10 80
(which means "replace any left brackets with empty strings (i.e. remove them) and any substrings that consist of a right bracket and a colon with a single space; then split the resulting string into a list")
it can be used to assign to variables like so:
lassign [split [string map {[ {} ]: { }} $addrport]] addr port
(which performs a sequential assign from the resulting list into two variables).
The scan command will also work:
scan $addrport {[%[^]]]:%d} addr port
(which means "after a left bracket, take a sequence of characters that does not include a right bracket, then skip a right bracket and a colon and then take a decimal number")
want the result as a list instead?
scan $addrport {[%[^]]]:%d}
# -> fec1::10 80
Even split works, in a slightly roundabout way:
set list [split $addrport {[]:}]
# -> {} fec1 {} 10 {} 80
set addr [lindex $list 1]::[lindex $list 3]
set port [lindex $list 5]
(note: this will have to be rewritten for addresses that are expanded to more than two groups).
Take your pick, but remember to be wary of regular expressions. Quicker, easier, more seductive they are, but always bite you in the ass in the end, they will.
(Note: the 'Hoodiecrow' mentioned in the comments is me, I used that nick earlier. Also note that at the time this question appeared I was still sceptical towards the ip module: today I swear by it. One is never to old to learn, hopefully.)
The ip package from the Tcl standard library can do that, and more.
One of the simplest ways to parse these sorts of things is with scan. It's the command that many Tclers forget!
set toParse {[fec1::10]:80}
scan $toParse {[%[a-f0-9:]]:%d} ip port
puts "host is $ip and port is $port"
The trick is that you want “scan charcters from limited set”. And in production code you want to check the result of scan, which should be the number of groups matched (2 in this case).

Templating MySQL's my.cnf for setup in Puppet

I have been tasked with templating MySQL's my.cnf in an attempt standardize the configuration amongst the slave databases using Puppet. Right now, I'm targeting the innodb settings.
Are there configuration options that can safely be calculated against hardware specifications such as memory, disk and procs?
You need facter.
puppet:/etc/puppet/modules/master/lib/facter$ cat disks.rb
#!/usr/bin/ruby
#require 'facter'
mount = `/bin/mount`
disks=Array.new
mount.split("\n").each_with_index { | disk,i |
unless disk.scan(/ext3|simfs|reiserfs|xfs/).empty?
d=disk.split[2]
disks.push d
disks.push ','
end
}
Facter.add('disks') do
setcode do
disks
end
end
`
and in puppet.pp i use facts $disks
#add disk check to zabbix
exec { "create_host":
command => "/bin/echo $fqdn $ipaddress $disks | do_work",
require => File["/root/ticket"],
subscribe => File["/root/ticket"],
refreshonly => true,
}
see "Adding Custom Facts to Facter" on puppet labs.
I'd be tempted to move the calculations into the erb file, for example the key_buffer_size is recommended to be set to 1/4 of the Systems RAM:
set-variable = key_buffer_size=<%= (memorysize.split(' ')[0].to_i * 1024) / 4 -%>M
there is no reason why you couldn't work on other variables available from Facter (number of processors etc) and come up with your own calculations to set other variables as above.
Remember ERB effectively provides a subset of Ruby so almost anything you can do in Ruby can be done in ERB.
puppet have the erb template, erb template can use the facter value ,like hostname or memor. and you can write you self facter shell script.