Can Ruby hashes be included in Sass and CoffeeScript, allowing data to be shared? Can Ruby hashes be included in Sass and CoffeeScript, allowing data to be shared? ruby ruby

Can Ruby hashes be included in Sass and CoffeeScript, allowing data to be shared?


You can turn your CoffeeScript and SASS into ERB templates which will be preprocessed (and thus you can use all awesome Ruby's possibilities in them). There is a little post that describes this: https://robots.thoughtbot.com/dont-repeat-your-ruby-constants-in-javascript.

Update

Add this code into lib/shared_assets_data.rb:

module SharedAssetsData  def self.colors_hash    { brandBackground: '#f00', brandForeground: '#00f', brandText: '#0f0' }  end  def self.sassify(hash)    hash.map do |key, value|      "#{key}: '#{value}'"    end.join(', ').prepend('( ').concat(' )')  end  def self.coffefy(hash)    hash.map do |key, value|      "#{key}: '#{value}'"    end.join(', ').prepend('{ ').concat(' }')  endend

Then to enable autoloading lib directory add this line to config/application.rb:

config.autoload_paths += %W(#{Rails.root}/lib)

After that you can do following:

# screen.sass.erb$colours: <%= SharedAssetsData.sassify(SharedAssetsData.colors_hash) %>body  background: map-get($colours, brandBackground)# screen.coffee.erbcolours = <%= SharedAssetsData.coffefy(SharedAssetsData.colors_hash) %>console.log colours.brandBackground


I think your best bet is to use gon. Gon is a gem that allows you to pass ruby variables to javascript/coffeescript. From there you can inline a style that makes use of the ruby hash.

Sass/CSS are really only about styles, and while Sass can have variables and do math, you shouldn't use it as a store for more complex data structures, this will make you code very difficult to maintain. Data storage and transport just isn't the job of Sass.

So, as for gon. Try something like this in your controller:

gon.ruby_hash = {key: value}

now in you coffeescript:

gon.ruby_hash

You'll be able to access the hash by calling gon.ruby_variable_name.