1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
# frozen_string_literal: true
class TimeagoStub
include Rails::Timeago::Helper
I18n.backend.store_translations :en, hello: 'World'
def time_tag(time, content, options = {})
options = options.map {|k, v| "#{k}=\"#{v}\"" }
"<time datetime=\"#{time.iso8601}\" #{options.join ' '}>#{content}</time>"
end
def time_ago_in_words(_time)
'%time_ago_in_words%'
end
def javascript_tag(source)
"<script>#{source}</script>"
end
end
class Application
attr_accessor :render
ASSET_BASE = Pathname.new(File.expand_path('../../..', __FILE__))
ASSET_DIRECTORIES = %w[lib/assets vendor/assets spec/support/assets].freeze
def initialize
@helper = TimeagoStub.new
end
def call(env)
@request = ::Rack::Request.new(env)
if @request.path =~ %r{^/assets/}
call_asset
else
[200, {'Content-Type' => 'text/html'}, [call_render]]
end
end
def call_render
body = if @render
@render.call(@helper, @request)
else
'<noscript></noscript>'
end
<<-HTML
<html>
<head>
<title></title>
<script src="/assets/javascripts/jquery.js"></script>
<script src="/assets/javascripts/jquery.timeago.js"></script>
<script src="/assets/javascripts/locales/jquery.timeago.de.js"></script>
<script src="/assets/javascripts/rails-timeago.js"></script>
#{@helper.timeago_script_tag}
</head>
<body>
#{body}
</body>
</html>
HTML
end
def call_asset
if (file = find_asset(@request.path[8..-1]))
[200, {'Content-Type' => 'text/javascript'}, [file.read]]
else
[404, {}, []]
end
end
def find_asset(path)
ASSET_DIRECTORIES.lazy.map do |dir|
ASSET_BASE.join(dir).join(path)
end.find(&:exist?)
end
class << self
def instance
@instance ||= new
end
def render(&block)
@instance.render = block
end
end
end
|