Module: Fortitude::Widget::Files::ClassMethods

Defined in:
lib/fortitude/widget/files.rb

Instance Method Summary collapse

Instance Method Details

#widget_class_from_file(filename, options = { }) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/fortitude/widget/files.rb', line 43

def widget_class_from_file(filename, options = { })
  options.assert_valid_keys(:root_dirs, :class_names_to_try, :magic_comment_text, :valid_base_classes)
  filename = File.expand_path(filename)
  source = File.read(filename)

  class_names_to_try = Array(options[:class_names_to_try])
  root_dirs = Array(options[:root_dirs])

  root_dirs.each do |root_dir|
    root_dir = File.expand_path(root_dir)

    if filename[0..(root_dir.length - 1)].downcase == root_dir.downcase
      subpath = filename[(root_dir.length + 1)..-1]
      subpath = $1 if subpath =~ %r{^(.*?)\.[^/]+$}i # remove all extensions
      class_names_to_try << subpath.camelize if subpath && subpath.length > 1
    end
  end

  widget_class_from_source(source,
    :class_names_to_try => class_names_to_try, :magic_comment_text => options[:magic_comment_text],
    :filename => filename, :valid_base_classes => options[:valid_base_classes])
end

#widget_class_from_source(source, options = { }) ⇒ Object



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
# File 'lib/fortitude/widget/files.rb', line 66

def widget_class_from_source(source, options = { })
  options.assert_valid_keys(:class_names_to_try, :magic_comment_text, :filename, :valid_base_classes)

  magic_comment_texts = Array(options[:magic_comment_text]) + DEFAULT_MAGIC_COMMENT_TEXTS
  all_class_names =
    magic_comment_class_from(source, magic_comment_texts) +
    Array(options[:class_names_to_try]) +
    scan_source_for_possible_class_names(source)

  out = widget_class_from_class_names(all_class_names, :valid_base_classes => options[:valid_base_classes])
  resulting_objects = out[:resulting_objects]

  unless out[:widget_class]
    if options[:filename]
      require options[:filename]
    else
      ::Object.class_eval(source)
    end

    out = widget_class_from_class_names(all_class_names, :valid_base_classes => options[:valid_base_classes])
    resulting_objects += out[:resulting_objects]
  end

  out[:widget_class] || (
    raise CannotDetermineWidgetClassNameError.new(all_class_names, :magic_comment_texts => magic_comment_texts,
      :filename => options[:filename], :resulting_objects => resulting_objects,
      :class_names_to_try => options[:class_names_to_try]))
end