Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sass support via sass-embedded #1911

Merged
merged 3 commits into from
May 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ jobs:
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
# Update rubygems due to https://github.com/rubygems/rubygems/pull/6490
rubygems: ${{ matrix.ruby == '3.0' && 'latest' || 'default' }}

- name: Run sinatra tests
continue-on-error: ${{ matrix.allow-failure || false }}
Expand Down
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ gem 'rainbows', platforms: [:mri] # uses #fork
gem 'rdiscount', platforms: [:ruby]
gem 'rdoc'
gem 'redcarpet', platforms: [:ruby]
gem 'sass-embedded', '~> 1.54'
gem 'simplecov', require: false
gem 'slim', '~> 4'
gem 'yajl-ruby', platforms: [:ruby]
Expand Down
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ pick up if available.
- [Erb Templates](#erb-templates)
- [Builder Templates](#builder-templates)
- [Nokogiri Templates](#nokogiri-templates)
- [Sass Templates](#sass-templates)
- [Scss Templates](#scss-templates)
- [Liquid Templates](#liquid-templates)
- [Markdown Templates](#markdown-templates)
- [RDoc Templates](#rdoc-templates)
Expand Down Expand Up @@ -649,6 +651,39 @@ It also takes a block for inline templates (see [example](#inline-templates)).

It also takes a block for inline templates (see [example](#inline-templates)).

#### Sass Templates

<table>
<tr>
<td>Dependency</td>
<td><a href="https://github.com/ntkme/sass-embedded-host-ruby" title="sass-embedded">sass-embedded</a></td>
</tr>
<tr>
<td>File Extension</td>
<td><tt>.sass</tt></td>
</tr>
<tr>
<td>Example</td>
<td><tt>sass :stylesheet, :style => :expanded</tt></td>
</tr>
</table>

#### Scss Templates

<table>
<tr>
<td>Dependency</td>
<td><a href="https://github.com/ntkme/sass-embedded-host-ruby" title="sass-embedded">sass-embedded</a></td>
</tr>
<tr>
<td>File Extension</td>
<td><tt>.scss</tt></td>
</tr>
<tr>
<td>Example</td>
<td><tt>scss :stylesheet, :style => :expanded</tt></td>
</tr>
</table>

#### Liquid Templates

Expand Down
22 changes: 20 additions & 2 deletions lib/sinatra/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,7 @@ def with_params(temp_params)
# Possible options are:
# :content_type The content type to use, same arguments as content_type.
# :layout If set to something falsy, no layout is rendered, otherwise
# the specified layout is used
# the specified layout is used (Ignored for `sass`)
# :layout_engine Engine to use for rendering the layout.
# :locals A hash with local variables that should be available
# in the template
Expand All @@ -752,6 +752,20 @@ def haml(template, options = {}, locals = {}, &block)
render(:haml, template, options, locals, &block)
end

def sass(template, options = {}, locals = {})
options[:default_content_type] = :css
options[:exclude_outvar] = true
options[:layout] = nil
render :sass, template, options, locals
end

def scss(template, options = {}, locals = {})
options[:default_content_type] = :css
options[:exclude_outvar] = true
options[:layout] = nil
render :scss, template, options, locals
end

def builder(template = nil, options = {}, locals = {}, &block)
options[:default_content_type] = :xml
render_ruby(:builder, template, options, locals, &block)
Expand Down Expand Up @@ -862,7 +876,11 @@ def render(engine, data, options = {}, locals = {}, &block)
catch(:layout_missing) { return render(layout_engine, layout, options, locals) { output } }
end

output.extend(ContentTyped).content_type = content_type if content_type
if content_type
# sass-embedded returns a frozen string
output = +output
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was this a problem before, that this string was frozen?

Maybe we should commit this change separately? With a test for it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is due to google-protobuf gem decodes the output as frozen string. There is a performance concern on eagerly unfreezing when not necessary. Therefore, sass-embedded returns the css output as frozen string as is, for which dependencies need to unfrozen the string as needed.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we only unfreeze when sass-embedded is used? Can we at least add a comment to the code with the above information?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a comment.

As for the +string method:

Returns self if self is not frozen.
Otherwise. returns self.dup, which is not frozen.

I did a microbenchmark on different ways to write this, and output = +output is the most performant one:

       user     system      total        real
s.freeze; s = s.dup if s.frozen?;	  1.553977   0.006994   1.560971 (  1.561001)
s.freeze; s = +s if s.frozen?;		  0.919195   0.002047   0.921242 (  0.921248)
s.freeze; s = +s;			  0.763196   0.001567   0.764763 (  0.764776)

output.extend(ContentTyped).content_type = content_type
end
output
end

Expand Down
10 changes: 10 additions & 0 deletions sinatra-contrib/lib/sinatra/engine_tracking.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ def haml?
@current_engine == :haml
end

# @return [Boolean] Returns true if current engine is `:sass`.
def sass?
@current_engine == :sass
end

# @return [Boolean] Returns true if current engine is `:scss`.
def scss?
@current_engine == :scss
end

# @return [Boolean] Returns true if current engine is `:builder`.
def builder?
@current_engine == :builder
Expand Down
2 changes: 1 addition & 1 deletion sinatra-contrib/lib/sinatra/namespace.rb
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ module NamespacedMethods
attr_reader :base, :templates

ALLOWED_ENGINES = %i[
erb erubi haml hamlit builder nokogiri
erb erubi haml hamlit builder nokogiri sass scss
liquid markdown rdoc asciidoc markaby
rabl slim yajl
]
Expand Down
1 change: 1 addition & 0 deletions sinatra-contrib/lib/sinatra/respond_with.rb
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ def self.jrubyify(engs)

def self.engines
engines = {
css: %i[sass scss],
xml: %i[builder nokogiri],
html: %i[erb erubi haml hamlit slim liquid
mab markdown rdoc],
Expand Down
1 change: 1 addition & 0 deletions sinatra-contrib/sinatra-contrib.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,6 @@ RubyGems 2.0 or newer is required to protect against public gem pushes. You can
s.add_development_dependency 'rake', '>= 12.3.3'
s.add_development_dependency 'redcarpet'
s.add_development_dependency 'rspec', '~> 3'
s.add_development_dependency 'sass-embedded', '~> 1.54'
s.add_development_dependency 'slim'
end
2 changes: 2 additions & 0 deletions sinatra-contrib/spec/respond_with/not_html.sass
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
body
color: red
86 changes: 86 additions & 0 deletions test/sass_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
require_relative 'test_helper'

begin
require 'sass-embedded'

class SassTest < Minitest::Test
def sass_app(options = {}, &block)
mock_app do
set :views, __dir__ + '/views'
set options
get('/', &block)
end
get '/'
end

it 'renders inline Sass strings' do
sass_app { sass "#sass\n background-color: white\n" }
assert ok?
assert_equal "#sass {\n background-color: white;\n}", body
end

it 'defaults content type to css' do
sass_app { sass "#sass\n background-color: white\n" }
assert ok?
assert_equal "text/css;charset=utf-8", response['Content-Type']
end

it 'defaults allows setting content type per route' do
sass_app do
content_type :html
sass "#sass\n background-color: white\n"
end
assert ok?
assert_equal "text/html;charset=utf-8", response['Content-Type']
end

it 'defaults allows setting content type globally' do
sass_app(:sass => { :content_type => 'html' }) {
sass "#sass\n background-color: white\n"
}
assert ok?
assert_equal "text/html;charset=utf-8", response['Content-Type']
end

it 'renders .sass files in views path' do
sass_app { sass :hello }
assert ok?
assert_equal "#sass {\n background-color: white;\n}", body
end

it 'ignores the layout option' do
sass_app { sass :hello, :layout => :layout2 }
assert ok?
assert_equal "#sass {\n background-color: white;\n}", body
end

it "raises error if template not found" do
mock_app { get('/') { sass :no_such_template } }
assert_raises(Errno::ENOENT) { get('/') }
end

it "passes SASS options to the Sass engine" do
sass_app do
sass(
"#sass\n background-color: white\n color: black\n",
:style => :compressed
)
end
assert ok?
assert_equal("#sass{background-color:#fff;color:#000}", body)
end

it "passes default SASS options to the Sass engine" do
mock_app do
set :sass, {:style => :compressed} # default Sass style is :expanded
get('/') { sass("#sass\n background-color: white\n color: black\n") }
end
get '/'
assert ok?
assert_equal "#sass{background-color:#fff;color:#000}", body
end
end

rescue LoadError
warn "#{$!}: skipping sass tests"
end
88 changes: 88 additions & 0 deletions test/scss_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
require_relative 'test_helper'

begin
require 'sass-embedded'

class ScssTest < Minitest::Test
def scss_app(options = {}, &block)
mock_app do
set :views, __dir__ + '/views'
set options
get('/', &block)
end
get '/'
end

it 'renders inline Scss strings' do
scss_app { scss "#scss {\n background-color: white; }\n" }
assert ok?
assert_equal "#scss {\n background-color: white;\n}", body
end

it 'defaults content type to css' do
scss_app { scss "#scss {\n background-color: white; }\n" }
assert ok?
assert_equal "text/css;charset=utf-8", response['Content-Type']
end

it 'defaults allows setting content type per route' do
scss_app do
content_type :html
scss "#scss {\n background-color: white; }\n"
end
assert ok?
assert_equal "text/html;charset=utf-8", response['Content-Type']
end

it 'defaults allows setting content type globally' do
scss_app(:scss => { :content_type => 'html' }) {
scss "#scss {\n background-color: white; }\n"
}
assert ok?
assert_equal "text/html;charset=utf-8", response['Content-Type']
end

it 'renders .scss files in views path' do
scss_app { scss :hello }
assert ok?
assert_equal "#scss {\n background-color: white;\n}", body
end

it 'ignores the layout option' do
scss_app { scss :hello, :layout => :layout2 }
assert ok?
assert_equal "#scss {\n background-color: white;\n}", body
end

it "raises error if template not found" do
mock_app { get('/') { scss(:no_such_template) } }
assert_raises(Errno::ENOENT) { get('/') }
end

it "passes scss options to the scss engine" do
scss_app do
scss(
"#scss {\n background-color: white;\n color: black\n}",
:style => :compressed
)
end
assert ok?
assert_equal "#scss{background-color:#fff;color:#000}", body
end

it "passes default scss options to the scss engine" do
mock_app do
set :scss, {:style => :compressed} # default scss style is :expanded
get('/') {
scss("#scss {\n background-color: white;\n color: black;\n}")
}
end
get '/'
assert ok?
assert_equal "#scss{background-color:#fff;color:#000}", body
end
end

rescue LoadError
warn "#{$!}: skipping scss tests"
end
2 changes: 2 additions & 0 deletions test/views/error.sass
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#sass
+argle-bargle
2 changes: 2 additions & 0 deletions test/views/hello.sass
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#sass
background-color: white
3 changes: 3 additions & 0 deletions test/views/hello.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#scss {
background-color: white
}