Gavin
Gavin

Reputation: 4333

Are controller instance variables accessible in the asset pipeline?

Given a file posts.js.coffee.erb in the asset pipeline, I can do this

  alert "<%= Rails.env %>"

but what about accessing instance variables defined in the controller?

  alert "<%= @posts.to_json %>"

Upvotes: 3

Views: 1324

Answers (2)

nir0
nir0

Reputation: 11

I think you need to alert this from the view, not a static js file.

Upvotes: 1

jgarcia
jgarcia

Reputation: 166

You can't. I was trying to add theming functionality to a blog application, and it turns out that it won't see the application helper methods or instance variables.

What I have done instead is create css view for the show action in themes, something like show.css.erb, which will be accessed via url like /themes/black.css

The same can be done with javascript, so if you need a specific javascript view just create a view for posts.js.erb

This technique is not even new in rails. I remember someone asking in twitter if you could do something like that in asp.net mvc back in 09

Additionally you will need to have your controller respond to that format, the following is a snippet from the app I was working on.

def show
  @theme = Theme.find(params[:id])

  respond_to do |format|
    format.html
    format.css
  end
end

Upvotes: 2

Related Questions