Skip to content

Commit

Permalink
Added support for data URI
Browse files Browse the repository at this point in the history
  • Loading branch information
vishalgarg231 committed Oct 8, 2016
1 parent 2a5f098 commit 4e29eb8
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/carrierwave/neo4j-data-uri.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require 'carrierwave'
require 'neo4j'
require "carrierwave/neo4j"
require 'carrierwave/neo4j_data_uri/tempfile'
require 'carrierwave/neo4j_data_uri/parser'
require 'carrierwave/neo4j_data_uri/mount'
23 changes: 23 additions & 0 deletions lib/carrierwave/neo4j_data_uri/mount.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module CarrierWave
module Neo4j
extend ActiveSupport::Concern

module ClassMethods
include CarrierWave::Mount
##
# See +CarrierWave::Mount#mount_uploader+ for documentation
#
def mount_uploader(column, uploader=nil, options={}, &block)
super

class_eval <<-RUBY, __FILE__, __LINE__+1
attr_accessor :#{column}_data_filename, :#{column}_data_mimetype
def #{column}_data_uri=(data)
self.#{column} = CarrierWave::Neo4j::DataUri::Parser.new(data).to_file original_filename: self.#{column}_data_filename, content_type: self.#{column}_data_mimetype
end
RUBY
end
end
end
end
38 changes: 38 additions & 0 deletions lib/carrierwave/neo4j_data_uri/parser.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
require 'base64'

module CarrierWave
module Neo4j
module DataUri
class Parser
attr_reader :type, :encoder, :data, :extension

def initialize(data_uri)
if data_uri.match /^data:(.*?);(.*?),(.*)$/
@type = $1
@encoder = $2
@data = $3
@extension = $1.split('/')[1]
else
raise ArgumentError, 'Invalid data'
end
end

def binary_data
@binary_data ||= Base64.decode64 data
end

def to_file(options = {})
@file ||= begin
file = Tempfile.new ['data_uri_upload', ".#{extension}"]
file.binmode
file << binary_data
file.rewind
file.original_filename = options[:original_filename]
file.content_type = options[:content_type]
file
end
end
end
end
end
end
19 changes: 19 additions & 0 deletions lib/carrierwave/neo4j_data_uri/tempfile.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
require 'tempfile'

module CarrierWave
module Neo4j
module DataUri
class Tempfile < ::Tempfile
attr_writer :original_filename, :content_type

def original_filename
@original_filename || File.basename(path)
end

def content_type
@content_type || MIME::Types.type_for(original_filename).first.content_type
end
end
end
end
end

0 comments on commit 4e29eb8

Please sign in to comment.