Can we use scss (sass-rails) in rails css.erb view files or is this just a asset pipeline thing?

562 Views Asked by At

I want to know, can we use scss in rails views eg

/views/home/home_stylesheet.css.scss.erb

$gray-medium-light : #eaeaea;

background: $gray-medium-light;

I tried changing the path format

<%= stylesheet_link_tag(about_me_user_path(current_user, format: :scss), media: 'all', class: "home_about_me_css") %>

And also in routes

get    'user_profile_stylesheet/:id'  => 'users#user_profile_stylesheet',  as: :user_profile_stylesheet, :defaults => { :format => 'scss' }

But rails seems to just convert the format back to css.

Can we use sass-rails gem to do this somehow?

Thanks.

EDIT I googled this with nothing coming up.

1

There are 1 best solutions below

7
On BEST ANSWER

Its theoretically possible by invoking the sass compiler. Note that you want to be using a request for css and not scss. There is no reason the client needs to know how the file is produced.

<%= stylesheet_link_tag(about_me_user_path(current_user, format: :css), media: 'all', class: "home_about_me_css") %>

class UsersController
  def user_profile_stylesheet
    respond_to do |f| 
      f.css do
        fn = Rails.root.join('app', 'views', 'home', 'home_stylesheet.css.scss.erb')
         # expand ERB template
        sass = render_to_string(file: fn)
        # run rendered template through the sass compiler
        css = SassC::Engine.new(sass, style: :compressed).render 
        render text: css
      end
    end  
  end
end   

I'm not so sure its something you really want to do in production as it requires you to compile sass at run-time when responding to requests. And you won't be able reference anything like SASS functions in your assets pipeline since this is compiled outside the pipeline.

Its also a security nightmare since SASS is not just declarative like CSS. And this could be exploited to execute code on your server.

Whatever you're trying to do there has to be a smarter / less complex solution.