Module: AnnotatedModels
- Defined in:
- lib/annotated_models.rb
Constant Summary collapse
- COMPAT_PREFIX =
Annotate Models plugin use this header
"== Schema Info"
- PREFIX =
"== Schema Information"
- END_MARK =
"== Schema Information End"
- PATTERN =
/^\n?# #{COMPAT_PREFIX}.*?\n(#.*\n)*\n/
- UNIT_TEST_DIR =
File.join for windows reverse bar compat? I dont use windows, can`t test
File.join("test", "unit" )
- SPEC_MODEL_DIR =
File.join("spec", "models")
- FIXTURE_TEST_DIR =
File.join("test", "fixtures")
- FIXTURE_SPEC_DIR =
File.join("spec", "fixtures")
- EXEMPLARS_TEST_DIR =
Object Daddy github.com/flogic/object_daddy/tree/master
File.join("test", "exemplars")
- EXEMPLARS_SPEC_DIR =
File.join("spec", "exemplars")
- BLUEPRINTS_TEST_DIR =
Machinist github.com/notahat/machinist
File.join("test", "blueprints")
- BLUEPRINTS_SPEC_DIR =
File.join("spec", "blueprints")
- FACTORY_GIRL_TEST_DIR =
Factory Girl github.com/thoughtbot/factory_girl
File.join("test", "factories")
- FACTORY_GIRL_SPEC_DIR =
File.join("spec", "factories")
- NO_LIMIT_COL_TYPES =
Don’t show limit (#) on these column types Example: show “integer” instead of “integer(4)”
["integer", "boolean"]
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_one_file(file_name, info_block, options = {}) ⇒ Object
Add a schema block to a file.
-
.do_annotations(options = {}) ⇒ Object
We’re passed a name of things that might be ActiveRecord models.
- .get_index_info(klass) ⇒ Object
-
.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 ⇒ Object
Return a list of the model files to annotate.
-
.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.
- .model_dir ⇒ Object
- .model_dir=(dir) ⇒ Object
-
.options_with_position(options, position_in) ⇒ Object
position = :position_in_fixture or :position_in_class.
-
.quote(value) ⇒ Object
Simple quoting for the default column value.
- .remove_annotation_of_file(file_name) ⇒ Object
- .remove_annotations(options = {}) ⇒ Object
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. Returns true or false depending on whether the source files were modified.
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 216 217 218 219 |
# File 'lib/annotated_models.rb', line 183 def annotate(klass, file, header,={}) info = get_schema_info(klass, header, ) annotated = false model_name = klass.name.underscore model_file_name = File.join(model_dir, file) if annotate_one_file(model_file_name, info, (, :position_in_class)) annotated = true end unless [:exclude_tests] [ File.join(UNIT_TEST_DIR, "#{model_name}_test.rb"), # test File.join(SPEC_MODEL_DIR, "#{model_name}_spec.rb"), # spec ].each do |file| # todo: add an option "position_in_test" -- or maybe just ask if anyone ever wants different positions for model vs. test vs. fixture annotate_one_file(file, info, (, :position_in_fixture)) if File.exist?(file) end end unless [:exclude_fixtures] [ File.join(FIXTURE_TEST_DIR, "#{klass.table_name}.yml"), # fixture File.join(FIXTURE_SPEC_DIR, "#{klass.table_name}.yml"), # fixture File.join(EXEMPLARS_TEST_DIR, "#{model_name}_exemplar.rb"), # Object Daddy File.join(EXEMPLARS_SPEC_DIR, "#{model_name}_exemplar.rb"), # Object Daddy File.join(BLUEPRINTS_TEST_DIR, "#{model_name}_blueprint.rb"), # Machinist Blueprints File.join(BLUEPRINTS_SPEC_DIR, "#{model_name}_blueprint.rb"), # Machinist Blueprints File.join(FACTORY_GIRL_TEST_DIR, "#{model_name}_factory.rb"), # Factory Girl Factories File.join(FACTORY_GIRL_SPEC_DIR, "#{model_name}_factory.rb"), # Factory Girl Factories ].each do |file| annotate_one_file(file, info, (, :position_in_fixture)) if File.exist?(file) end end annotated end |
.annotate_one_file(file_name, info_block, 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)
:position<Symbol>:: where to place the annotated section in fixture or model file,
"before" or "after". Default is "before".
:position_in_class<Symbol>:: where to place the annotated section in model file
:position_in_fixture<Symbol>:: where to place the annotated section in fixture file
:position_in_others<Symbol>:: where to place the annotated section in the rest of
supported files
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/annotated_models.rb', line 143 def annotate_one_file(file_name, info_block, ={}) if File.exist?(file_name) old_content = File.read(file_name) # Ignore the Schema version line because it changes with each migration header = Regexp.new(/(^# Table name:.*?\n(#.*\n)*\n)/) old_header = old_content.match(header).to_s new_header = info_block.match(header).to_s if old_header == new_header false else # Remove old schema info old_content.sub!(PATTERN, '') # Write it back new_content = [:position].to_s == 'after' ? (old_content + "\n" + info_block) : (info_block + old_content) File.open(file_name, "wb") { |f| f.puts new_content } true end end 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
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'lib/annotated_models.rb', line 268 def do_annotations(={}) if [:require] [:require].each do |path| require path end end header = PREFIX.dup if [:include_version] version = ActiveRecord::Migrator.current_version rescue 0 if version > 0 header << "\n# Schema version: #{version}" end end if [:model_dir] self.model_dir = [:model_dir] end annotated = [] get_model_files.each do |file| begin klass = get_model_class(file) if klass < ActiveRecord::Base && !klass.abstract_class? if annotate(klass, file, header, ) annotated << klass end end rescue Exception => e puts "Unable to annotate #{file}: #{e.} (#{e.backtrace.first})" end end if annotated.empty? puts "Nothing annotated." else puts "Annotated (#{annotated.length}): #{annotated.join(', ')}" end end |
.get_index_info(klass) ⇒ Object
116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/annotated_models.rb', line 116 def get_index_info(klass) index_info = "#\n# Indexes\n#\n" indexes = klass.connection.indexes(klass.table_name) return "" if indexes.empty? max_size = indexes.collect{|index| index.name.size}.max + 1 indexes.each do |index| index_info << sprintf("# %-#{max_size}.#{max_size}s %s %s", index.name, "(#{index.columns.join(",")})", index.unique ? "UNIQUE" : "").rstrip + "\n" end return index_info 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.
253 254 255 256 257 258 259 260 261 262 |
# File 'lib/annotated_models.rb', line 253 def get_model_class(file) require File.("#{model_dir}/#{file}") # this is for non-rails projects, which don't get Rails auto-require magic model = file.gsub(/\.rb$/, '').camelize parts = model.split('::') begin parts.inject(Object) {|klass, part| klass.const_get(part) } rescue LoadError, NameError Object.const_get(parts.last) end end |
.get_model_files ⇒ Object
Return a list of the model files to annotate. If we have command line arguments, they’re assumed to be either the underscore or CamelCase versions of model names. Otherwise we take all the model files in the model_dir directory.
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
# File 'lib/annotated_models.rb', line 231 def get_model_files models = ARGV.dup models.shift models.reject!{|m| m.match(/^(.*)=/)} if models.empty? begin Dir.chdir(model_dir) do models = Dir["**/*.rb"] end rescue SystemCallError puts "No models found in directory '#{model_dir}'." puts "Either specify models on the command line, or use the --model-dir option." puts "Call 'annotate --help' for more info." exit 1; end end models 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
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
# File 'lib/annotated_models.rb', line 55 def get_schema_info(klass, header, = {}) info = "# #{header}\n#\n" info << "# Table name: #{klass.table_name}\n" info << "# Human name: #{klass.model_name.human}\n" unless klass.model_name.human(:default => "").blank? info << "#\n" max_size = klass.column_names.map{|name| name.size}.max + (ENV['format_rdoc'] ? 5 : 1) klass.columns.each do |col| attrs = [] attrs << "'#{klass.human_attribute_name(col.name)}'" unless klass.human_attribute_name(col.name, :default => "").blank? attrs << "default(#{quote(col.default)})" unless col.default.nil? attrs << "not null" unless col.null attrs << "primary key" if col.name.to_sym == klass.primary_key.to_sym col_type = col.type.to_s if col_type == "decimal" col_type << "(#{col.precision}, #{col.scale})" else if (col.limit) col_type << "(#{col.limit})" unless NO_LIMIT_COL_TYPES.include?(col_type) end end # Check out if we got a geometric column # and print the type and SRID if col.respond_to?(:geometry_type) attrs << "#{col.geometry_type}, #{col.srid}" end # Check if the column has indices and print "indexed" if true # If the indice include another colum, print it too. if [:simple_indexes] # Check out if this column is indexed indices = klass.connection.indexes(klass.table_name) if indices = indices.select { |ind| ind.columns.include? col.name } indices.each do |ind| ind = ind.columns.reject! { |i| i == col.name } attrs << (ind.length == 0 ? "indexed" : "indexed => [#{ind.join(", ")}]") end end end if ENV['format_rdoc'] info << sprintf("# %-#{max_size}.#{max_size}s<tt>%s</tt>", "*#{col.name}*::", attrs.unshift(col_type).join(", ")).rstrip + "\n" else info << sprintf("# %-#{max_size}.#{max_size}s:%-15.15s %s", col.name, col_type, attrs.join(", ")).rstrip + "\n" end end if [:show_indexes] info << get_index_info(klass) end if ENV['format_rdoc'] info << "#--\n" info << "# #{END_MARK}\n" info << "#++\n\n" else info << "#\n\n" end end |
.model_dir ⇒ Object
29 30 31 |
# File 'lib/annotated_models.rb', line 29 def model_dir @model_dir || "app/models" end |
.model_dir=(dir) ⇒ Object
33 34 35 |
# File 'lib/annotated_models.rb', line 33 def model_dir=(dir) @model_dir = dir end |
.options_with_position(options, position_in) ⇒ Object
position = :position_in_fixture or :position_in_class
222 223 224 |
# File 'lib/annotated_models.rb', line 222 def (, position_in) .merge(:position=>([position_in] || [:position])) end |
.quote(value) ⇒ Object
Simple quoting for the default column value
38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/annotated_models.rb', line 38 def quote(value) case value when NilClass then "NULL" when TrueClass then "TRUE" when FalseClass then "FALSE" when Float, Fixnum, Bignum then value.to_s # BigDecimals need to be output in a non-normalized form and quoted. when BigDecimal then value.to_s('F') else value.inspect end end |
.remove_annotation_of_file(file_name) ⇒ Object
167 168 169 170 171 172 173 174 175 |
# File 'lib/annotated_models.rb', line 167 def remove_annotation_of_file(file_name) if File.exist?(file_name) content = File.read(file_name) content.sub!(PATTERN, '') File.open(file_name, "wb") { |f| f.puts content } end end |
.remove_annotations(options = {}) ⇒ Object
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
# File 'lib/annotated_models.rb', line 308 def remove_annotations(={}) if [:model_dir] puts "removing" self.model_dir = [:model_dir] end deannotated = [] get_model_files.each do |file| begin klass = get_model_class(file) if klass < ActiveRecord::Base && !klass.abstract_class? deannotated << klass model_name = klass.name.underscore model_file_name = File.join(model_dir, file) remove_annotation_of_file(model_file_name) [ File.join(UNIT_TEST_DIR, "#{model_name}_test.rb"), File.join(SPEC_MODEL_DIR, "#{model_name}_spec.rb"), File.join(FIXTURE_TEST_DIR, "#{klass.table_name}.yml"), # fixture File.join(FIXTURE_SPEC_DIR, "#{klass.table_name}.yml"), # fixture File.join(EXEMPLARS_TEST_DIR, "#{model_name}_exemplar.rb"), # Object Daddy File.join(EXEMPLARS_SPEC_DIR, "#{model_name}_exemplar.rb"), # Object Daddy File.join(BLUEPRINTS_TEST_DIR, "#{model_name}_blueprint.rb"), # Machinist Blueprints File.join(BLUEPRINTS_SPEC_DIR, "#{model_name}_blueprint.rb"), # Machinist Blueprints File.join(FACTORY_GIRL_TEST_DIR, "#{model_name}_factory.rb"), # Factory Girl Factories File.join(FACTORY_GIRL_SPEC_DIR, "#{model_name}_factory.rb"), # Factory Girl Factories ].each do |file| remove_annotation_of_file(file) if File.exist?(file) end end rescue Exception => e puts "Unable to annotate #{file}: #{e.}" end end puts "Removed annotation from: #{deannotated.join(', ')}" end |