Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lazy load image content #137

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions lib/sablon/content.rb
Original file line number Diff line number Diff line change
Expand Up @@ -184,15 +184,23 @@ def inspect
"#<Image #{name}:#{@rid_by_file}>"
end

# image data being lazily loaded by procs, we need to actually execute
# the procs to test that the generated images are the same
def ==(other)
self.class == other.class &&
name == other.name && properties == other.properties &&
data.call == other.data.call
end

def initialize(source, attributes = {})
attributes = Hash[attributes.map { |k, v| [k.to_s, v] }]
# If the source object is readable, use it as such otherwise open
# and read the content
# and lazily read the content
if source.respond_to?(:read)
name, img_data = process_readable(source, attributes)
else
name = File.basename(source)
img_data = IO.binread(source)
img_data = -> { IO.binread(source) }
end
#
super name, img_data
Expand Down Expand Up @@ -233,8 +241,8 @@ def process_readable(source, attributes)
raise ArgumentError, "Error: Could not determine filename from source, try: `Sablon.content(readable_obj, filename: '...')`"
end
end
#
[File.basename(name), source.read]
# delay loading the image with a lambda
[File.basename(name), -> { source.read } ]
end

# Convert centimeters or inches to Word specific emu format
Expand Down
2 changes: 1 addition & 1 deletion lib/sablon/operations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def set_local_rid(env, image)
rel_attr = {
Type: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'
}
rid = env.document.add_media(image.name, image.data, rel_attr)
rid = env.document.add_media(image.name, image.data.call, rel_attr)
image.rid_by_file[env.document.current_entry] = rid
elsif image.rid_by_file[env.document.current_entry].nil?
# locate an existing relationship and duplicate it
Expand Down