Module: AnnotateModels
- Defined in:
- lib/annotate/annotate_models.rb,
lib/annotate/annotate_models/file_patterns.rb
Defined Under Namespace
Modules: FilePatterns Classes: BadModelFileError
Constant Summary collapse
- COMPAT_PREFIX =
Annotate Models plugin use this header
'== Schema Info'- COMPAT_PREFIX_MD =
'## Schema Info'- PREFIX =
'== Schema Information'- PREFIX_MD =
'## Schema Information'- END_MARK =
'== Schema Information End'- SKIP_ANNOTATION_PREFIX =
'# -\*- SkipSchemaAnnotations'- MATCHED_TYPES =
%w[test fixture factory serializer scaffold controller helper].freeze
- NO_LIMIT_COL_TYPES =
Don't show limit (#) on these column types Example: show "integer" instead of "integer(4)"
%w[integer bigint boolean].freeze
- NO_DEFAULT_COL_TYPES =
Don't show default value for these column types
%w[json jsonb hstore].freeze
- INDEX_CLAUSES =
{ unique: { default: 'UNIQUE', markdown: '_unique_' }, where: { default: 'WHERE', markdown: '_where_' }, using: { default: 'USING', markdown: '_using_' } }.freeze
- MAGIC_COMMENT_MATCHER =
/(^#\s*encoding:.*(?:\n|r\n))|(^# coding:.*(?:\n|\r\n))|(^# -\*- coding:.*(?:\n|\r\n))|(^# -\*- encoding\s?:.*(?:\n|\r\n))|(^#\s*frozen_string_literal:.+(?:\n|\r\n))|(^# -\*- frozen_string_literal\s*:.+-\*-(?:\n|\r\n))/
Class Attribute Summary collapse
Class Method Summary collapse
-
.annotate(klass, file, header, options = {}) ⇒ Object
Given the name of an ActiveRecord class, create a schema info block (basically a comment containing information on the columns and their types) and put it at the front of the model and fixture source files.
- .annotate_model_file(annotated, file, header, options) ⇒ Object
-
.annotate_one_file(file_name, info_block, position, options = {}) ⇒ Object
Add a schema block to a file.
- .annotate_pattern(options = {}) ⇒ Object
- .classified_sort(cols) ⇒ Object
-
.do_annotations(options = {}) ⇒ Object
We're passed a name of things that might be ActiveRecord models.
- .expand_glob_into_files(glob) ⇒ Object
- .final_index_string(index, max_size) ⇒ Object
- .final_index_string_in_markdown(index) ⇒ Object
- .get_check_constraint_info(klass, options = {}) ⇒ Object
- .get_col_type(col) ⇒ Object
- .get_foreign_key_info(klass, options = {}) ⇒ Object
- .get_index_info(klass, options = {}) ⇒ Object
-
.get_loaded_model(model_path, file) ⇒ Object
Retrieve loaded model class.
-
.get_loaded_model_by_path(model_path) ⇒ Object
Retrieve loaded model class by path to the file where it's supposed to be defined.
-
.get_model_class(file) ⇒ Object
Retrieve the classes belonging to the model names we're asked to process Check for namespaced models in subdirectories as well as models in subdirectories without namespacing.
-
.get_model_files(options) ⇒ Object
Return a list of the model files to annotate.
- .get_patterns(options, pattern_types = []) ⇒ Object
- .get_schema_footer_text(_klass, options = {}) ⇒ Object
- .get_schema_header_text(klass, options = {}) ⇒ Object
-
.get_schema_info(klass, header, options = {}) ⇒ Object
Use the column information in an ActiveRecord class to create a comment block containing a line for each column.
- .hide_default?(col_type, options) ⇒ Boolean
- .hide_limit?(col_type, options) ⇒ Boolean
- .index_columns_info(index) ⇒ Object
- .index_unique_info(index, format = :default) ⇒ Object
- .index_using_info(index, format = :default) ⇒ Object
- .index_where_info(index, format = :default) ⇒ Object
- .list_model_files_from_argument ⇒ Object
- .magic_comments_as_string(content) ⇒ Object
- .matched_types(options) ⇒ Object
-
.options_with_position(options, position_in) ⇒ Object
position = :position_in_fixture or :position_in_class.
- .parse_options(options = {}) ⇒ Object
-
.quote(value) ⇒ Object
Simple quoting for the default column value.
- .remove_annotation_of_file(file_name, options = {}) ⇒ Object
- .remove_annotations(options = {}) ⇒ Object
- .resolve_filename(filename_template, model_name, table_name) ⇒ Object
- .retrieve_indexes_from_table(klass) ⇒ Object
- .schema_default(klass, column) ⇒ Object
- .split_model_dir(option_value) ⇒ Object
Class Attribute Details
.model_dir ⇒ Object
55 56 57 |
# File 'lib/annotate/annotate_models.rb', line 55 def model_dir @model_dir.is_a?(Array) ? @model_dir : [@model_dir || 'app/models'] end |
.root_dir ⇒ Object
61 62 63 64 65 66 67 68 69 |
# File 'lib/annotate/annotate_models.rb', line 61 def root_dir if @root_dir.blank? [''] elsif @root_dir.is_a?(String) @root_dir.split(',') else @root_dir end end |
.skip_subdirectory_model_load ⇒ Object
71 72 73 74 75 76 77 78 79 80 |
# File 'lib/annotate/annotate_models.rb', line 71 def skip_subdirectory_model_load # This option is set in options[:skip_subdirectory_model_load] # and stops the get_loaded_model method from loading a model from a subdir if @skip_subdirectory_model_load.blank? false else @skip_subdirectory_model_load end end |
Class Method Details
.annotate(klass, file, header, options = {}) ⇒ Object
Given the name of an ActiveRecord class, create a schema info block (basically a comment containing information on the columns and their types) and put it at the front of the model and fixture source files.
Options (opts)
:position_in_class
Returns:
an array of file names that were annotated.
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 |
# File 'lib/annotate/annotate_models.rb', line 548 def annotate(klass, file, header, = {}) begin klass.reset_column_information info = get_schema_info(klass, header, ) model_name = klass.name.underscore table_name = klass.table_name model_file_name = File.join(file) annotated = [] if annotate_one_file(model_file_name, info, :position_in_class, (, :position_in_class)) annotated << model_file_name end matched_types().each do |key| exclusion_key = :"exclude_#{key.pluralize}" position_key = :"position_in_#{key}" # Same options for active_admin models if key == 'admin' exclusion_key = :exclude_class position_key = :position_in_class end next if [exclusion_key] get_patterns(, key) .map { |f| resolve_filename(f, model_name, table_name) } .map { |f| (f) } .flatten .each do |f| annotated << f if annotate_one_file(f, info, position_key, (, position_key)) end end rescue StandardError => e warn "Unable to annotate #{file}: #{e.}" warn "\t" + e.backtrace.join("\n\t") if [:trace] end annotated end |
.annotate_model_file(annotated, file, header, options) ⇒ Object
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 |
# File 'lib/annotate/annotate_models.rb', line 743 def annotate_model_file(annotated, file, header, ) return false if /#{SKIP_ANNOTATION_PREFIX}.*/ =~ (File.exist?(file) ? File.read(file) : '') klass = get_model_class(file) do_annotate = klass.is_a?(Class) && klass < ActiveRecord::Base && (![:exclude_sti_subclasses] || !(klass.superclass < ActiveRecord::Base && klass.table_name == klass.superclass.table_name)) && !klass.abstract_class? && klass.table_exists? annotated.concat(annotate(klass, file, header, )) if do_annotate rescue BadModelFileError => e unless [:ignore_unknown_models] warn "Unable to annotate #{file}: #{e.}" warn "\t" + e.backtrace.join("\n\t") if [:trace] end rescue StandardError => e warn "Unable to annotate #{file}: #{e.}" warn "\t" + e.backtrace.join("\n\t") if [:trace] end |
.annotate_one_file(file_name, info_block, position, options = {}) ⇒ Object
Add a schema block to a file. If the file already contains a schema info block (a comment starting with "== Schema Information"), check if it matches the block that is already there. If so, leave it be. If not, remove the old info block and write a new one.
Returns:
true or false depending on whether the file was modified.
Options (opts)
:force
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 |
# File 'lib/annotate/annotate_models.rb', line 435 def annotate_one_file(file_name, info_block, position, = {}) return false unless File.exist?(file_name) old_content = File.read(file_name) return false if old_content =~ /#{SKIP_ANNOTATION_PREFIX}.*\n/ # Ignore the Schema version line because it changes with each migration header_pattern = /(^# Table name:.*?\n(#.*[\r]?\n)*[\r]?)/ old_header = old_content.match(header_pattern).to_s new_header = info_block.match(header_pattern).to_s column_pattern = /^#[\t ]+[\w\*\.`]+[\t ]+.+$/ old_columns = old_header && old_header.scan(column_pattern).sort new_columns = new_header && new_header.scan(column_pattern).sort return false if old_columns == new_columns && ![:force] if [:frozen] abort "annotate error. #{file_name} needs to be updated, but annotate was run with `--frozen`." end # Replace inline the old schema info with the new schema info wrapper_open = [:wrapper_open] ? "# #{[:wrapper_open]}\n" : '' wrapper_close = [:wrapper_close] ? "# #{[:wrapper_close]}\n" : '' wrapped_info_block = "#{wrapper_open}#{info_block}#{wrapper_close}" old_annotation = old_content.match(annotate_pattern()).to_s # if there *was* no old schema info or :force was passed, we simply # need to insert it in correct position if old_annotation.empty? || [:force] magic_comments_block = magic_comments_as_string(old_content) old_content.gsub!(MAGIC_COMMENT_MATCHER, '') old_content.sub!(annotate_pattern(), '') new_content = if %w[after bottom].include?([position].to_s) magic_comments_block + (old_content.rstrip + "\n\n" + wrapped_info_block) elsif magic_comments_block.empty? magic_comments_block + wrapped_info_block + old_content.lstrip else magic_comments_block + "\n" + wrapped_info_block + old_content.lstrip end else # replace the old annotation with the new one # keep the surrounding whitespace the same space_match = old_annotation.match(/\A(?<start>\s*).*?\n(?<end>\s*)\z/m) new_annotation = space_match[:start] + wrapped_info_block + space_match[:end] new_content = old_content.sub(annotate_pattern(), new_annotation) end File.open(file_name, 'wb') { |f| f.puts new_content } true end |
.annotate_pattern(options = {}) ⇒ Object
47 48 49 50 51 52 53 |
# File 'lib/annotate/annotate_models.rb', line 47 def annotate_pattern( = {}) if [:wrapper_open] return /(?:^(\n|\r\n)?# (?:#{[:wrapper_open]}).*(\n|\r\n)?# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?(\n|\r\n)(#.*(\n|\r\n))*(\n|\r\n)*)|^(\n|\r\n)?# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?(\n|\r\n)(#.*(\n|\r\n))*(\n|\r\n)*/ end /^(\n|\r\n)?# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?(\n|\r\n)(#.*(\n|\r\n))*(\n|\r\n)*/ end |
.classified_sort(cols) ⇒ Object
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 |
# File 'lib/annotate/annotate_models.rb', line 804 def classified_sort(cols) rest_cols = [] = [] associations = [] id = nil cols.each do |c| if c.name.eql?('id') id = c elsif c.name.eql?('created_at') || c.name.eql?('updated_at') << c elsif c.name[-3, 3].eql?('_id') associations << c else rest_cols << c end end [rest_cols, , associations].each { |a| a.sort_by!(&:name) } ([id] << rest_cols << << associations).flatten.compact end |
.do_annotations(options = {}) ⇒ Object
We're passed a name of things that might be ActiveRecord models. If we can find the class, and if its a subclass of ActiveRecord::Base, then pass it to the associated block
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 |
# File 'lib/annotate/annotate_models.rb', line 716 def do_annotations( = {}) () header = [:format_markdown] ? PREFIX_MD.dup : PREFIX.dup version = begin ActiveRecord::Migrator.current_version rescue StandardError 0 end header << "\n# Schema version: #{version}" if [:include_version] && version > 0 annotated = [] get_model_files().each do |path, filename| annotate_model_file(annotated, File.join(path, filename), header, ) end if annotated.empty? puts 'Model files unchanged.' else puts "Annotated (#{annotated.length}): #{annotated.join(', ')}" end end |
.expand_glob_into_files(glob) ⇒ Object
739 740 741 |
# File 'lib/annotate/annotate_models.rb', line 739 def (glob) Dir.glob(glob) end |
.final_index_string(index, max_size) ⇒ Object
321 322 323 324 325 326 327 328 329 330 |
# File 'lib/annotate/annotate_models.rb', line 321 def final_index_string(index, max_size) format( "# %-#{max_size}.#{max_size}s %s%s%s%s", index.name, "(#{index_columns_info(index).join(',')})", index_unique_info(index), index_where_info(index), index_using_info(index) ).rstrip + "\n" end |
.final_index_string_in_markdown(index) ⇒ Object
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
# File 'lib/annotate/annotate_models.rb', line 304 def final_index_string_in_markdown(index) details = format( '%s%s%s', index_unique_info(index, :markdown), index_where_info(index, :markdown), index_using_info(index, :markdown) ).strip details = " (#{details})" unless details.blank? format( "# * `%s`%s:\n# * **`%s`**\n", index.name, details, index_columns_info(index).join("`**\n# * **`") ) end |
.get_check_constraint_info(klass, options = {}) ⇒ Object
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
# File 'lib/annotate/annotate_models.rb', line 393 def get_check_constraint_info(klass, = {}) cc_info = if [:format_markdown] String.new("#\n# ### Check Constraints\n#\n") else String.new("#\n# Check Constraints\n#\n") end return '' unless klass.connection.respond_to?(:supports_check_constraints?) && klass.connection.supports_check_constraints? && klass.connection.respond_to?(:check_constraints) check_constraints = klass.connection.check_constraints(klass.table_name) return '' if check_constraints.empty? max_size = check_constraints.map { |check_constraint| check_constraint.name.size }.max + 1 check_constraints.sort_by(&:name).each do |check_constraint| expression = check_constraint.expression ? "(#{check_constraint.expression.squish})" : nil cc_info << if [:format_markdown] cc_info_markdown = format('# * `%s`', check_constraint.name) cc_info_markdown << format(': `%s`', expression) if expression cc_info_markdown << "\n" else format("# %-#{max_size}.#{max_size}s %s", check_constraint.name, expression).rstrip + "\n" end end cc_info end |
.get_col_type(col) ⇒ Object
264 265 266 267 268 269 270 |
# File 'lib/annotate/annotate_models.rb', line 264 def get_col_type(col) if (col.respond_to?(:bigint?) && col.bigint?) || /\Abigint\b/ =~ col.sql_type 'bigint' else (col.type || col.sql_type).to_s end.dup end |
.get_foreign_key_info(klass, options = {}) ⇒ Object
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
# File 'lib/annotate/annotate_models.rb', line 354 def get_foreign_key_info(klass, = {}) fk_info = if [:format_markdown] String.new("#\n# ### Foreign Keys\n#\n") else String.new("#\n# Foreign Keys\n#\n") end return '' unless klass.connection.respond_to?(:supports_foreign_keys?) && klass.connection.supports_foreign_keys? && klass.connection.respond_to?(:foreign_keys) foreign_keys = klass.connection.foreign_keys(klass.table_name) return '' if foreign_keys.empty? format_name = lambda do |fk| return fk.[:column] if fk.name.blank? [:show_complete_foreign_keys] ? fk.name : fk.name.gsub(/(?<=^fk_rails_)[0-9a-f]{10}$/, '...') end max_size = foreign_keys.map(&format_name).map(&:size).max + 1 foreign_keys.sort_by { |fk| [format_name.call(fk), fk.column] }.each do |fk| ref_info = "#{fk.column} => #{fk.to_table}.#{fk.primary_key}" constraints_info = String.new('') constraints_info += "ON DELETE => #{fk.on_delete} " if fk.on_delete constraints_info += "ON UPDATE => #{fk.on_update} " if fk.on_update constraints_info.strip! fk_info << if [:format_markdown] format("# * `%s`%s:\n# * **`%s`**\n", format_name.call(fk), constraints_info.blank? ? '' : " (_#{constraints_info}_)", ref_info) else format("# %-#{max_size}.#{max_size}s %s %s", format_name.call(fk), "(#{ref_info})", constraints_info).rstrip + "\n" end end fk_info end |
.get_index_info(klass, options = {}) ⇒ Object
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
# File 'lib/annotate/annotate_models.rb', line 242 def get_index_info(klass, = {}) index_info = if [:format_markdown] String.new("#\n# ### Indexes\n#\n") else String.new("#\n# Indexes\n#\n") end indexes = retrieve_indexes_from_table(klass) return '' if indexes.empty? max_size = indexes.collect { |index| index.name.size }.max + 1 indexes.sort_by(&:name).each do |index| index_info << if [:format_markdown] final_index_string_in_markdown(index) else final_index_string(index, max_size) end end index_info end |
.get_loaded_model(model_path, file) ⇒ Object
Retrieve loaded model class
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 |
# File 'lib/annotate/annotate_models.rb', line 670 def get_loaded_model(model_path, file) unless skip_subdirectory_model_load loaded_model_class = get_loaded_model_by_path(model_path) return loaded_model_class if loaded_model_class end # We cannot get loaded model when `model_path` is loaded by Rails # auto_load/eager_load paths. Try all possible model paths one by one. absolute_file = File.(file) model_paths = $LOAD_PATH.map(&:to_s) .select { |path| absolute_file.include?(path) } .map { |path| absolute_file.sub(path, '').sub(/\.rb$/, '').sub(%r{^/}, '') } model_paths .map { |path| get_loaded_model_by_path(path) } .find { |loaded_model| !loaded_model.nil? } end |
.get_loaded_model_by_path(model_path) ⇒ Object
Retrieve loaded model class by path to the file where it's supposed to be defined.
689 690 691 692 693 694 695 696 697 698 699 |
# File 'lib/annotate/annotate_models.rb', line 689 def get_loaded_model_by_path(model_path) ActiveSupport::Inflector.constantize(ActiveSupport::Inflector.camelize(model_path)) rescue StandardError, LoadError # Revert to the old way but it is not really robust ObjectSpace.each_object(::Class) .select do |c| c.is_a?(Class) && # NOTE: we use === to avoid a bug in activesupport 2.3.14 OptionMerger vs. is_a? c.ancestors.respond_to?(:include?) && # to fix FactoryGirl bug, see https://github.com/ctran/annotate_models/pull/82 c.ancestors.include?(ActiveRecord::Base) end.detect { |c| ActiveSupport::Inflector.underscore(c.to_s) == model_path } end |
.get_model_class(file) ⇒ Object
Retrieve the classes belonging to the model names we're asked to process Check for namespaced models in subdirectories as well as models in subdirectories without namespacing.
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 |
# File 'lib/annotate/annotate_models.rb', line 650 def get_model_class(file) model_path = file.gsub(/\.rb$/, '') model_dir.each { |dir| model_path = model_path.gsub(/^#{dir}/, '').gsub(%r{^/}, '') } begin get_loaded_model(model_path, file) || raise(BadModelFileError) rescue LoadError # this is for non-rails projects, which don't get Rails auto-require magic file_path = File.(file) if File.file?(file_path) && Kernel.require(file_path) retry elsif model_path =~ %r{/} model_path = model_path.split('/')[1..].join('/').to_s retry else raise end end end |
.get_model_files(options) ⇒ Object
Return a list of the model files to annotate. If we have command line arguments, they're assumed to the path of model files from root dir. Otherwise we take all the model files in the model_dir directory.
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 |
# File 'lib/annotate/annotate_models.rb', line 599 def get_model_files() model_files = [] model_files = list_model_files_from_argument unless [:is_rake] return model_files unless model_files.empty? model_dir.each do |dir| Dir.chdir(dir) do list = if [:ignore_model_sub_dir] Dir['*.rb'].map { |f| [dir, f] } else Dir['**/*.rb'].reject { |f| f['concerns/'] }.map { |f| [dir, f] } end model_files.concat(list) end end model_files rescue SystemCallError warn "No models found in directory '#{model_dir.join("', '")}'." warn 'Either specify models on the command line, or use the --model-dir option.' warn "Call 'annotate --help' for more info." exit 1 end |
.get_patterns(options, pattern_types = []) ⇒ Object
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/annotate/annotate_models.rb', line 82 def get_patterns(, pattern_types = []) current_patterns = [] root_dir.each do |root_directory| Array(pattern_types).each do |pattern_type| patterns = FilePatterns.generate(root_directory, pattern_type, ) current_patterns += if pattern_type.to_sym == :additional_file_patterns patterns else patterns.map { |p| p.sub(%r{^[/]*}, '') } end end end current_patterns end |
.get_schema_footer_text(_klass, options = {}) ⇒ Object
230 231 232 233 234 235 236 237 238 239 240 |
# File 'lib/annotate/annotate_models.rb', line 230 def (_klass, = {}) info = String.new('') if [:format_rdoc] info << "#--\n" info << "# #{END_MARK}\n" info << "#++\n" else info << "#\n" end info end |
.get_schema_header_text(klass, options = {}) ⇒ Object
217 218 219 220 221 222 223 224 225 226 227 228 |
# File 'lib/annotate/annotate_models.rb', line 217 def get_schema_header_text(klass, = {}) info = String.new("#\n") # Create a new mutable string if [:format_markdown] info << "# Table name: `#{klass.table_name}`\n" info << "#\n" info << "# ### Columns\n" else info << "# Table name: #{klass.table_name}\n" end info << "#\n" info end |
.get_schema_info(klass, header, options = {}) ⇒ Object
Use the column information in an ActiveRecord class to create a comment block containing a line for each column. The line contains the column name, the type (and length), and any optional attributes
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
# File 'lib/annotate/annotate_models.rb', line 137 def get_schema_info(klass, header, = {}) # rubocop:disable Metrics/MethodLength info = String.new("# #{header}\n") info << get_schema_header_text(klass, ) max_size = max_schema_info_width(klass, ) md_names_overhead = 6 md_type_allowance = 18 = 16 if [:format_markdown] info << format( "# %-#{max_size + md_names_overhead}.#{max_size + md_names_overhead}s | %-#{md_type_allowance}.#{md_type_allowance}s | %s\n", 'Name', 'Type', 'Attributes' ) info << "# #{'-' * (max_size + md_names_overhead)} | #{'-' * md_type_allowance} | #{'-' * 27}\n" end cols = columns(klass, ) with_comments = with_comments?(klass, ) with_comments_column = with_comments_column?(klass, ) # Precalculate Values = cols.to_h do |col| col_comment = with_comments || with_comments_column ? col.comment&.gsub("\n", '\\n') : nil col_type = get_col_type(col) attrs = get_attributes(col, col_type, klass, ) col_name = if with_comments && col_comment "#{col.name}(#{col_comment})" else col.name end simple_formatted_attrs = attrs.join(', ') [col.name, { col_type: col_type, attrs: attrs, col_name: col_name, simple_formatted_attrs: simple_formatted_attrs, col_comment: col_comment }] end # Output annotation = .map { |_, m| m[:simple_formatted_attrs].length }.max cols.each do |col| col_type = [col.name][:col_type] attrs = [col.name][:attrs] col_name = [col.name][:col_name] simple_formatted_attrs = [col.name][:simple_formatted_attrs] col_comment = [col.name][:col_comment] if [:format_rdoc] info << (format("# %-#{max_size}.#{max_size}s<tt>%s</tt>", "*#{col_name}*::", attrs.unshift(col_type).join(', ')).rstrip + "\n") elsif [:format_yard] info << (sprintf("# @!attribute #{col_name}") + "\n") ruby_class = col.respond_to?(:array) && col.array ? "Array<#{map_col_type_to_ruby_classes(col_type)}>" : map_col_type_to_ruby_classes(col_type) info << (sprintf("# @return [#{ruby_class}]") + "\n") elsif [:format_markdown] name_remainder = max_size - col_name.length - non_ascii_length(col_name) type_remainder = (md_type_allowance - 2) - col_type.length info << (format("# **`%s`**%#{name_remainder}s | `%s`%#{type_remainder}s | `%s`", col_name, ' ', col_type, ' ', attrs.join(', ').rstrip).gsub( '``', ' ' ).rstrip + "\n") elsif with_comments_column info << format_default(col_name, max_size, col_type, , simple_formatted_attrs, , col_comment) else info << format_default(col_name, max_size, col_type, , simple_formatted_attrs) end end info << get_index_info(klass, ) if [:show_indexes] && klass.table_exists? info << get_foreign_key_info(klass, ) if [:show_foreign_keys] && klass.table_exists? info << get_check_constraint_info(klass, ) if [:show_check_constraints] && klass.table_exists? info << (klass, ) end |
.hide_default?(col_type, options) ⇒ Boolean
343 344 345 346 347 348 349 350 351 352 |
# File 'lib/annotate/annotate_models.rb', line 343 def hide_default?(col_type, ) excludes = if [:hide_default_column_types].blank? NO_DEFAULT_COL_TYPES else [:hide_default_column_types].split(',') end excludes.include?(col_type) end |
.hide_limit?(col_type, options) ⇒ Boolean
332 333 334 335 336 337 338 339 340 341 |
# File 'lib/annotate/annotate_models.rb', line 332 def hide_limit?(col_type, ) excludes = if [:hide_limit_column_types].blank? NO_LIMIT_COL_TYPES else [:hide_limit_column_types].split(',') end excludes.include?(col_type) end |
.index_columns_info(index) ⇒ Object
272 273 274 275 276 277 278 279 280 |
# File 'lib/annotate/annotate_models.rb', line 272 def index_columns_info(index) Array(index.columns).map do |col| if index.try(:orders) && index.orders[col.to_s] "#{col} #{index.orders[col.to_s].upcase}" else col.to_s.gsub("\r", '\r').gsub("\n", '\n') end end end |
.index_unique_info(index, format = :default) ⇒ Object
282 283 284 |
# File 'lib/annotate/annotate_models.rb', line 282 def index_unique_info(index, format = :default) index.unique ? " #{INDEX_CLAUSES[:unique][format]}" : '' end |
.index_using_info(index, format = :default) ⇒ Object
295 296 297 298 299 300 301 302 |
# File 'lib/annotate/annotate_models.rb', line 295 def index_using_info(index, format = :default) value = index.try(:using) && index.using.try(:to_sym) if !value.blank? && value != :btree " #{INDEX_CLAUSES[:using][format]} #{value}" else '' end end |
.index_where_info(index, format = :default) ⇒ Object
286 287 288 289 290 291 292 293 |
# File 'lib/annotate/annotate_models.rb', line 286 def index_where_info(index, format = :default) value = index.try(:where).try(:to_s) if value.blank? '' else " #{INDEX_CLAUSES[:where][format]} #{value}" end end |
.list_model_files_from_argument ⇒ Object
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 |
# File 'lib/annotate/annotate_models.rb', line 625 def list_model_files_from_argument return [] if ARGV.empty? specified_files = ARGV.map { |file| File.(file) } model_files = model_dir.flat_map do |dir| absolute_dir_path = File.(dir) specified_files .find_all { |file| file.start_with?(absolute_dir_path) } .map { |file| [dir, file.sub("#{absolute_dir_path}/", '')] } end if model_files.size != specified_files.size puts "The specified file could not be found in directory '#{model_dir.join("', '")}'." puts "Call 'annotate --help' for more info." exit 1 end model_files end |
.magic_comments_as_string(content) ⇒ Object
491 492 493 494 495 496 497 498 499 |
# File 'lib/annotate/annotate_models.rb', line 491 def magic_comments_as_string(content) magic_comments = content.scan(MAGIC_COMMENT_MATCHER).flatten.compact if magic_comments.any? magic_comments.join else '' end end |
.matched_types(options) ⇒ Object
517 518 519 520 521 522 523 |
# File 'lib/annotate/annotate_models.rb', line 517 def matched_types() types = MATCHED_TYPES.dup types << 'admin' if [:active_admin] =~ Annotate::Constants::TRUE_RE && !types.include?('admin') types << 'additional_file_patterns' if [:additional_file_patterns].present? types end |
.options_with_position(options, position_in) ⇒ Object
position = :position_in_fixture or :position_in_class
591 592 593 |
# File 'lib/annotate/annotate_models.rb', line 591 def (, position_in) .merge(position: [position_in] || [:position]) end |
.parse_options(options = {}) ⇒ Object
701 702 703 704 705 |
# File 'lib/annotate/annotate_models.rb', line 701 def ( = {}) self.model_dir = split_model_dir([:model_dir]) if [:model_dir] self.root_dir = [:root_dir] if [:root_dir] self.skip_subdirectory_model_load = [:skip_subdirectory_model_load].present? end |
.quote(value) ⇒ Object
Simple quoting for the default column value
99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/annotate/annotate_models.rb', line 99 def quote(value) case value when NilClass then 'NULL' when TrueClass then 'TRUE' when FalseClass then 'FALSE' when Float, Integer then value.to_s # BigDecimals need to be output in a non-normalized form and quoted. when BigDecimal then value.to_s('F') when Array then value.map { |v| quote(v) } else value.inspect end end |
.remove_annotation_of_file(file_name, options = {}) ⇒ Object
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
# File 'lib/annotate/annotate_models.rb', line 501 def remove_annotation_of_file(file_name, = {}) if File.exist?(file_name) content = File.read(file_name) return false if content =~ /#{SKIP_ANNOTATION_PREFIX}.*\n/ wrapper_open = [:wrapper_open] ? "# #{[:wrapper_open]}\n" : '' content.sub!(/(#{wrapper_open})?#{annotate_pattern()}/, '') File.open(file_name, 'wb') { |f| f.puts content } true else false end end |
.remove_annotations(options = {}) ⇒ Object
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 |
# File 'lib/annotate/annotate_models.rb', line 764 def remove_annotations( = {}) () deannotated = [] deannotated_klass = false get_model_files().each do |file| file = File.join(file) begin klass = get_model_class(file) if klass < ActiveRecord::Base && !klass.abstract_class? model_name = klass.name.underscore table_name = klass.table_name model_file_name = file deannotated_klass = true if remove_annotation_of_file(model_file_name, ) get_patterns(, matched_types()) .map { |f| resolve_filename(f, model_name, table_name) } .each do |f| if File.exist?(f) remove_annotation_of_file(f, ) deannotated_klass = true end end end deannotated << klass if deannotated_klass rescue StandardError => e warn "Unable to deannotate #{File.join(file)}: #{e.}" warn "\t" + e.backtrace.join("\n\t") if [:trace] end end puts "Removed annotations from: #{deannotated.join(', ')}" end |
.resolve_filename(filename_template, model_name, table_name) ⇒ Object
797 798 799 800 801 802 |
# File 'lib/annotate/annotate_models.rb', line 797 def resolve_filename(filename_template, model_name, table_name) filename_template .gsub('%MODEL_NAME%', model_name) .gsub('%PLURALIZED_MODEL_NAME%', model_name.pluralize) .gsub('%TABLE_NAME%', table_name || model_name.pluralize) end |
.retrieve_indexes_from_table(klass) ⇒ Object
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
# File 'lib/annotate/annotate_models.rb', line 117 def retrieve_indexes_from_table(klass) table_name = klass.table_name return [] unless table_name indexes = klass.connection.indexes(table_name) return indexes if indexes.any? || !klass.table_name_prefix # Try to search the table without prefix table_name_without_prefix = table_name.to_s.sub(klass.table_name_prefix, '') if klass.connection.table_exists?(table_name_without_prefix) klass.connection.indexes(table_name_without_prefix) else [] end end |
.schema_default(klass, column) ⇒ Object
113 114 115 |
# File 'lib/annotate/annotate_models.rb', line 113 def schema_default(klass, column) quote(klass.column_defaults[column.name]) end |
.split_model_dir(option_value) ⇒ Object
707 708 709 710 |
# File 'lib/annotate/annotate_models.rb', line 707 def split_model_dir(option_value) option_value = option_value.split(',') unless option_value.is_a?(Array) option_value.map(&:strip).reject(&:empty?) end |