Skip to content

Instantly share code, notes, and snippets.

@greypants
Last active December 15, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greypants/5271747 to your computer and use it in GitHub Desktop.
Save greypants/5271747 to your computer and use it in GitHub Desktop.
RUBY / COMPASS: Save global javascript variable references to generated sprite names
# Store javascript references to sprites in spriteList.js
# Author: dan.tello@viget.com
on_sprite_saved do |file_path|
# Path to file where sprite data is to be stored
javascript_file = "public/javascripts/base/compass_sprites.js"
path_segments = file_path.split('/public').last.split('/')
file_name = path_segments.pop
image_path = path_segments.join('/') + '/'
base_folder = path_segments[2]
parent_folder = path_segments[path_segments.length - 1]
sprite_name = file_name.gsub(/\-(\w*)\.png/, "");
# Prefix the sprite name with its parent foldername if the sprite
# file is not a direct child of the base_folder.
file_prefix = base_folder == parent_folder ? "" : parent_folder + "_"
sprite_variable = "COMPASS.#{base_folder}.#{file_prefix}#{sprite_name}"
javascript = File.read(javascript_file)
# Create COMPASS object if it doesn't exist
unless javascript =~ /COMPASS = \{\};/
File.open(javascript_file, "a") do |f|
f.write("COMPASS = {};\n")
end
end
# Add the scope/section object if it doesn't exist
unless javascript =~ /COMPASS\.#{base_folder} = \{\};/
File.open(javascript_file, "a") do |f|
f.write("\nCOMPASS.#{base_folder} = {};")
end
end
# Add or replace the sprite reference
if javascript =~ /#{sprite_variable} =\ /
File.open(javascript_file, "w") do |f|
f.puts javascript.gsub(/#{sprite_variable} = (.*);/, "#{sprite_variable} = '#{file_name}';")
end
else
File.open(javascript_file, "a") do |f|
f.write("\n#{sprite_variable} = '#{file_name}';")
end
end
end
// Example of the generated output if
// file_path === '/public/images/clever_world/module/map/parts-s63d8b5c4ed.png'
COMPASS = {};
COMPASS.clever_world = {};
COMPASS.clever_world.map_parts = 'parts-s63d8b5c4ed.png';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment