Class: EmbeddedImage

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Fields::Serializable
Defined in:
lib/transit/support/embedded_image.rb

Overview

Adds support for embedding images directly into a document as Base64 strings. These images can then be used as data uris inline in html or served via rack handler.

Defined Under Namespace

Classes: ImageData

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data



8
9
10
# File 'lib/transit/support/embedded_image.rb', line 8

def data
  @data
end

Instance Method Details

#deserialize(image_data) ⇒ Object

Called on load from the database



42
43
44
45
# File 'lib/transit/support/embedded_image.rb', line 42

def deserialize(image_data)
  return self.class.new unless image_data
  ::Marshal.load(::Base64.decode64(image_data)) 
end

#serialize(image_data) ⇒ Object

Called on store to the database



50
51
52
53
# File 'lib/transit/support/embedded_image.rb', line 50

def serialize(image_data)
  set_data(image_data)
  ::Base64.encode64(::Marshal.dump(self))
end

#set_data(image_data) ⇒ Object

Stores the image data to be serialized on save. If an uploaded file, or image based object is provided the object is stored as-is. If raw data is passed, an instance of ImageData is generated for compatability.



31
32
33
34
35
36
37
# File 'lib/transit/support/embedded_image.rb', line 31

def set_data(image_data)
  unless image_data.respond_to?(:content_type)
    @data = image_data.to_s
  else
    @data = ImageData.new(image_data)
  end
end

#to_sObject

If the stored data is a string, return it directly. Otherwise, base64 encode the image data and format into a string suitable for using in html.



60
61
62
63
# File 'lib/transit/support/embedded_image.rb', line 60

def to_s
  return data unless data.is_a?(ImageData)
  "data:#{data.content_type};base64,#{::Base64.encode64(data.body)}"
end