PageRenderTime 67ms CodeModel.GetById 35ms app.highlight 12ms RepoModel.GetById 18ms 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
 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
 7require 'diagram_graph'
 8
 9# Root class for RailRoad diagrams
10class AppDiagram
11
12  def initialize(options)
13    @options = options
14    @graph = DiagramGraph.new
15    @graph.show_label = @options.label
16
17    STDERR.print "Loading application environment\n" if @options.verbose
18    load_environment
19
20    STDERR.print "Loading application classes\n" if @options.verbose
21    load_classes
22  end
23
24  # Print diagram
25  def print
26    if @options.output
27      old_stdout = STDOUT.dup
28      begin
29        STDOUT.reopen(@options.output)
30      rescue
31        STDERR.print "Error: Cannot write diagram to #{@options.output}\n\n"
32        exit 2
33      end
34    end
35    
36    if @options.xmi 
37        STDERR.print "Generating XMI diagram\n" if @options.verbose
38    	STDOUT.print @graph.to_xmi
39    else
40        STDERR.print "Generating DOT graph\n" if @options.verbose
41        STDOUT.print @graph.to_dot 
42    end
43
44    if @options.output
45      STDOUT.reopen(old_stdout)
46    end
47  end # print
48
49  private 
50
51  # Prevents Rails application from writing to STDOUT
52  def disable_stdout
53    @old_stdout = STDOUT.dup
54    STDOUT.reopen(PLATFORM =~ /mswin/ ? "NUL" : "/dev/null")
55  end
56
57  # Restore STDOUT  
58  def enable_stdout
59    STDOUT.reopen(@old_stdout)
60  end
61
62
63  # Print error when loading Rails application
64  def print_error(type)
65    STDERR.print "Error loading #{type}.\n  (Are you running " +
66                 "#{RailRoad::APP_NAME} on the aplication's root directory?)\n\n"
67  end
68
69  # Load Rails application's environment
70  def load_environment
71    begin
72      disable_stdout
73      require "config/environment"
74      enable_stdout
75    rescue LoadError
76      enable_stdout
77      print_error "application environment"
78      raise
79    end
80  end
81
82  # Extract class name from filename, respecting modules
83  def extract_class_name(filename)
84    class_name = File.basename(filename).chomp(".rb").camelize
85    rooted_filename = filename.sub(Rails.root, '').sub(/^app\/\w+?\//, '').sub(/^lib/, '')
86    module_names = rooted_filename.split('/')[0..-2].map(&:camelize).join('::')
87    module_names.present? ? module_names << '::' << class_name : class_name
88  end
89
90end # class AppDiagram