Module: InlineImage
- Defined in:
- lib/inline_image.rb,
lib/inline_image/version.rb
Constant Summary collapse
- MAX_FILE_SIZE =
Maximum file size to be inlined in bytes
1024
- VERSION =
"1.0.1"
Class Method Summary collapse
- .process(base_dir, name_in_file, max_file_size = MAX_FILE_SIZE) ⇒ Object
- .replace_in_css(css_text, base_dir = '.', max_file_size = MAX_FILE_SIZE) ⇒ Object
- .replace_in_html(html_text, base_dir = '.', max_file_size = MAX_FILE_SIZE) ⇒ Object
Instance Method Summary collapse
Class Method Details
.process(base_dir, name_in_file, max_file_size = MAX_FILE_SIZE) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/inline_image.rb', line 40 def self.process(base_dir, name_in_file, max_file_size = MAX_FILE_SIZE) image_filename = "#{base_dir}/#{name_in_file}" extension = name_in_file.split('.').last if File.exist?(image_filename) and File.size(image_filename) <= max_file_size then File.open(image_filename) do |img| base64encoded = Base64.encode64(img.read).gsub("\n", "") "data:image/#{extension};base64,#{base64encoded}" end if File.exist? image_filename else name_in_file end end |
.replace_in_css(css_text, base_dir = '.', max_file_size = MAX_FILE_SIZE) ⇒ Object
28 29 30 31 32 |
# File 'lib/inline_image.rb', line 28 def self.replace_in_css(css_text, base_dir = '.', max_file_size = MAX_FILE_SIZE) css_text.gsub(/url\(['"]?([^'"\)]+)['"]?\)/m) do |match| "url(#{process(base_dir, $1, max_file_size)})" end end |
.replace_in_html(html_text, base_dir = '.', max_file_size = MAX_FILE_SIZE) ⇒ Object
34 35 36 37 38 |
# File 'lib/inline_image.rb', line 34 def self.replace_in_html(html_text, base_dir = '.', max_file_size = MAX_FILE_SIZE) html_text.gsub(/src=['"]([^'"\)]+)['"]/m) do |match| "src=\"#{process(base_dir, $1, max_file_size)}\"" end end |
Instance Method Details
#in_css(filename, max_file_size = MAX_FILE_SIZE, options = {}) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/inline_image.rb', line 9 def in_css(filename, max_file_size = MAX_FILE_SIZE, = {}) return false unless File.exist? filename # TODO : Option to disable the copy FileUtils.cp filename, "#{filename}.bak" dir = File.dirname(filename) extension = filename.split('.').last File.open(filename, File::RDWR) do |file| css = replace_in_css file.read, dir file.rewind file.truncate(0) file.write css end end |