Module: AutoSprite

Defined in:
lib/auto_sprite.rb

Defined Under Namespace

Modules: Helpers

Constant Summary collapse

SPRITE_ASSETS_PATH =
File.join(RAILS_ROOT, 'public', 'images',      'sprites')
CSS_FILE_PATH =
File.join(RAILS_ROOT, 'public', 'stylesheets', 'auto_sprite.css')
SPRITE_IMG_PATH =
File.join(RAILS_ROOT, 'public', 'images',      'auto_sprite.png')
SPRITE_IMG_URL =
'/images/auto_sprite.png'

Class Method Summary collapse

Class Method Details

.generate_css_name(f) ⇒ Object



21
22
23
24
25
# File 'lib/auto_sprite.rb', line 21

def generate_css_name(f)
  filename = File.basename(f).gsub(/\?.*$/, "")
  filename.tr!('.', "_")
  "_as_#{filename}"
end

.setup!Object



27
28
29
30
31
32
# File 'lib/auto_sprite.rb', line 27

def setup!
  FileUtils::mkdir_p(SPRITE_ASSETS_PATH)
  FileUtils::rm_f(CSS_FILE_PATH)   
  FileUtils::rm_f(SPRITE_IMG_PATH)
  write_new_assets
end

.sprite_file_namesObject



15
16
17
18
19
# File 'lib/auto_sprite.rb', line 15

def sprite_file_names
  Dir.entries(SPRITE_ASSETS_PATH).reject { |f| 
    !File.file?(File.join(SPRITE_ASSETS_PATH,f))
  }
end

.sprite_file_pathsObject



11
12
13
# File 'lib/auto_sprite.rb', line 11

def sprite_file_paths
  sprite_file_names.map {|f| File.join(SPRITE_ASSETS_PATH, f) }
end

.write_new_assetsObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/auto_sprite.rb', line 34

def write_new_assets
  unless sprite_file_paths.empty?
    image_list = Magick::ImageList.new(*sprite_file_paths)
    image_list.append(true).write(SPRITE_IMG_PATH)
    all_class_names = sprite_file_names.map { |x| '.' + generate_css_name(x) }
    pos = 0
    File.open(CSS_FILE_PATH, "w") do |f|
      image_list.each do |img|
        css_class = generate_css_name(img.filename)
        f << ".#{css_class}{background-position:0 #{pos * -1}px;height:#{img.rows}px;width:#{img.columns}px;}"
        pos = pos + img.rows;
      end
      f << all_class_names.join(",")
      f << "{display:inline-block;background-image:url('#{SPRITE_IMG_URL}');background-repeat:no-repeat;}"
    end
  end
end