Class: HelpfulComments::ModelSchemas
- Defined in:
- lib/helpful_comments/model_schemas.rb
Instance Method Summary collapse
-
#build ⇒ Object
builds the lines to be put into the top of the file.
-
#initialize(klass) ⇒ ModelSchemas
constructor
takes a descendant of ActiveRecord::Base.
-
#load ⇒ Object
puts the comments into the file.
Methods inherited from Base
Constructor Details
#initialize(klass) ⇒ ModelSchemas
takes a descendant of ActiveRecord::Base
5 6 7 8 9 10 |
# File 'lib/helpful_comments/model_schemas.rb', line 5 def initialize(klass) unless klass < ActiveRecord::Base raise ArgumentError, 'klass must descend from ActiveRecord::Base' end @klass = klass end |
Instance Method Details
#build ⇒ Object
builds the lines to be put into the top of the file
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/helpful_comments/model_schemas.rb', line 13 def build results = [%w[Field Type Null Default]] @klass.columns_hash.each do |name, column| default = case column.default when NilClass then '' when TrueClass then '1' when FalseClass then '0' else column.default end results << [name, column.sql_type, column.null ? 'YES' : 'NO', default] end lengths = results.transpose.map { |list| list.max_by { |segment| segment.to_s.length }.length + 1 } definition = results.map do |line| '# ' + line.map.with_index { |segment, index| "| %-#{lengths[index]}s" % segment }.join + "|\n" end header_line = '# ' + lengths.map { |length| '+' + '-' * (length + 1) }.join + "+\n" [header_line, definition.first, header_line] + definition[1..-1] + [header_line] end |
#load ⇒ Object
puts the comments into the file
34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/helpful_comments/model_schemas.rb', line 34 def load @comments = self.build max_size = @comments.size written = false load_comments(Rails.root.join('app', 'models').to_s, max_size) do |file, line| if !written and line.lstrip.starts_with?('class') and !file.trailing?(@comments) file.write(@comments.join) written = true end file.write(line) end end |