Skip to content
This repository has been archived by the owner on May 16, 2021. It is now read-only.

JavascriptHeader module #99

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -30,6 +30,9 @@ Currently included:
* `sinatra/engine_tracking`: Adds methods like `haml?` that allow helper
methods to check whether they are called from within a template.

* `sinatra/javascript_header`: Helpers for `script` HTML tags. Adds `javascript`
helper method.

* `sinatra/json`: Adds a `#json` helper method to return JSON documents.

* `sinatra/link_header`: Helpers for generating `link` HTML tags and
Expand Down
1 change: 1 addition & 0 deletions lib/sinatra/contrib.rb
Expand Up @@ -16,6 +16,7 @@ module Common
helpers :ContentFor
helpers :Cookies
helpers :EngineTracking
helpers :JavascriptHeader
helpers :JSON
helpers :LinkHeader
helpers :Streaming
Expand Down
56 changes: 56 additions & 0 deletions lib/sinatra/javascript_header.rb
@@ -0,0 +1,56 @@
require 'sinatra/base'

module Sinatra

# = Sinatra::JavascriptHeader
#
# <tt>Sinatra::JavascriptHeader</tt> adds a set of helper methods to generate script
# HTML tags.
#
# == Usage
#
# Once you had set up the helpers in your application (see below), you will
# be able to call the following methods from inside your templates:
#
# +javascript+::
# Returns HTML script tags to use the given javascript files.
#
# === Classic Application
#
# In a classic application simply require the helpers, and start using them:
#
# require 'sinatra'
# require 'sinatra/javascript_header'
#
# # The rest of your classic application code goes here...
#
# === Modular Application
#
# In a modular application you need to require the helpers, and then tell
# the application you will use them:
#
# require 'sinatra/base'
# require 'sinatra/javascript_header'
#
# class MyApp < Sinatra::Base
# helpers Sinatra::JavascriptHeader
#
# # The rest of your modular application code goes here...
# end
#
module JavascriptHeader
##
# Returns HTML script tags to use the given javascript files
#
# Example:
#
# javascript '/a.js', '/b.js'
def javascript(*urls)
tag = "<script src=\"%s\" type=\"text/javascript\"></script>"

urls.map { |url| tag % url }.join "\n"
end
end

helpers JavascriptHeader
end
21 changes: 21 additions & 0 deletions spec/javascript_header_spec.rb
@@ -0,0 +1,21 @@
require 'backports'
require_relative 'spec_helper'

describe Sinatra::JavascriptHeader do
before do
mock_app do
helpers Sinatra::JavascriptHeader

get '/application' do
javascript '/application.js'
end
end
end

describe :javascript do
it 'returns the html script tag' do
get '/application'
body.should match(%r{^<script src="/application\.js"})
end
end
end