Last active
December 15, 2015 14:08
-
-
Save greypants/5271747 to your computer and use it in GitHub Desktop.
RUBY / COMPASS: Save global javascript variable references to generated sprite names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Store javascript references to sprites in spriteList.js | |
# Author: [email protected] | |
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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