class String
def line_from_index(index)
lines = self.to_a
running_length = 0
lines.each_with_index do |line, i|
running_length += line.length
if running_length > index
return i
end
end
end
end
class FootnoteFilter
cattr_accessor :no_style, :abs_root, :textmate_prefix
self.no_style = false
self.textmate_prefix = "txmt://open?url=file://"
attr_accessor :body, :abs_root
def self.filter(controller)
return if controller.render_without_footnotes
filter = FootnoteFilter.new(controller)
filter.add_footnotes!
end
def initialize(controller)
@controller = controller
@template = controller.instance_variable_get("@template")
@body = controller.response.body
@extra_html = ""
self.abs_root = File.expand_path(RAILS_ROOT)
end
def add_footnotes!
if performed_render? and first_render?
if ["rhtml", "rxhtml"].include?(template_extension) && (content_type =~ /html/ || content_type.nil?) && !xhr?
# If the user would like to be responsible for the styles, let them opt out of the styling here
insert_styles unless FootnoteFilter.no_style
insert_footnotes
end
end
rescue Exception => e
# Discard footnotes if there are any problems
RAILS_DEFAULT_LOGGER.error "Textmate Footnotes Exception: #{e}\n#{e.backtrace.join("\n")}"
end
# Some controller classes come with the Controller:: module and some don't
# (anyone know why? -- Duane)
def controller_filename
File.join(abs_root, "app", "controllers", "#{@controller.class.to_s.underscore}.rb").
sub('/controllers/controllers/', '/controllers/')
end
def controller_text
@controller_text ||= IO.read(controller_filename)
end
def index_of_method
(controller_text =~ /def\s+#{@controller.action_name}[\s\(]/)
end
def controller_line_number
controller_text.line_from_index(index_of_method)
end
def performed_render?
@controller.instance_variable_get("@performed_render")
end
def first_render?
@template.respond_to?(:first_render) and @template.first_render
end
def xhr?
@controller.request.xhr?
end
def template_path
@template.first_render.sub(/\.(rhtml|rxhtml|rxml|rjs)$/, "")
end
def template_extension
@template.first_render.scan(/\.(rhtml|rxhtml|rxml|rjs)$/).flatten.first ||
@template.pick_template_extension(template_path).to_s
end
def template_file_name
File.expand_path(@template.send(:full_template_path, template_path, template_extension))
end
def layout_file_name
File.expand_path(@template.send(:full_template_path, @controller.active_layout, "rhtml"))
end
def content_type
@controller.response.headers['Content-Type']
end
def stylesheet_files
@stylesheet_files ||= @body.scan(/]+href\s*=\s*['"]([^>?'"]+)/im).flatten
end
def javascript_files
@javascript_files ||= @body.scan(/