PageRenderTime 46ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/app_diagram.rb

http://github.com/speartail/RailRoad
Ruby | 90 lines | 62 code | 16 blank | 12 comment | 7 complexity | ec1a7b540bf561a2d14097a0c092144a MD5 | raw file
Possible License(s): GPL-2.0
  1. # RailRoad - RoR diagrams generator
  2. # http://railroad.rubyforge.org
  3. #
  4. # Copyright 2007-2008 - Javier Smaldone (http://www.smaldone.com.ar)
  5. # See COPYING for more details
  6. require 'diagram_graph'
  7. # Root class for RailRoad diagrams
  8. class AppDiagram
  9. def initialize(options)
  10. @options = options
  11. @graph = DiagramGraph.new
  12. @graph.show_label = @options.label
  13. STDERR.print "Loading application environment\n" if @options.verbose
  14. load_environment
  15. STDERR.print "Loading application classes\n" if @options.verbose
  16. load_classes
  17. end
  18. # Print diagram
  19. def print
  20. if @options.output
  21. old_stdout = STDOUT.dup
  22. begin
  23. STDOUT.reopen(@options.output)
  24. rescue
  25. STDERR.print "Error: Cannot write diagram to #{@options.output}\n\n"
  26. exit 2
  27. end
  28. end
  29. if @options.xmi
  30. STDERR.print "Generating XMI diagram\n" if @options.verbose
  31. STDOUT.print @graph.to_xmi
  32. else
  33. STDERR.print "Generating DOT graph\n" if @options.verbose
  34. STDOUT.print @graph.to_dot
  35. end
  36. if @options.output
  37. STDOUT.reopen(old_stdout)
  38. end
  39. end # print
  40. private
  41. # Prevents Rails application from writing to STDOUT
  42. def disable_stdout
  43. @old_stdout = STDOUT.dup
  44. STDOUT.reopen(PLATFORM =~ /mswin/ ? "NUL" : "/dev/null")
  45. end
  46. # Restore STDOUT
  47. def enable_stdout
  48. STDOUT.reopen(@old_stdout)
  49. end
  50. # Print error when loading Rails application
  51. def print_error(type)
  52. STDERR.print "Error loading #{type}.\n (Are you running " +
  53. "#{RailRoad::APP_NAME} on the aplication's root directory?)\n\n"
  54. end
  55. # Load Rails application's environment
  56. def load_environment
  57. begin
  58. disable_stdout
  59. require "config/environment"
  60. enable_stdout
  61. rescue LoadError
  62. enable_stdout
  63. print_error "application environment"
  64. raise
  65. end
  66. end
  67. # Extract class name from filename, respecting modules
  68. def extract_class_name(filename)
  69. class_name = File.basename(filename).chomp(".rb").camelize
  70. rooted_filename = filename.sub(Rails.root, '').sub(/^app\/\w+?\//, '').sub(/^lib/, '')
  71. module_names = rooted_filename.split('/')[0..-2].map(&:camelize).join('::')
  72. module_names.present? ? module_names << '::' << class_name : class_name
  73. end
  74. end # class AppDiagram