Module: GridAttachment::Mongomatic::ClassMethods

Defined in:
lib/grid_attachment/mongomatic.rb

Instance Method Summary collapse

Instance Method Details

#attachment(name, options = {}) ⇒ Object

Declare an attachment for the object

eg: attachment :image



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/grid_attachment/mongomatic.rb', line 31

def attachment(name,options={})
  prefix = options[:prefix] ||= :grid

  ##
  # Add this name to the attachment_types
  attachment_types.push(name).uniq!

  ##
  # Return the Grid object.
  # eg: image.filename, image.read
  define_method(name) do
    grid.get(self["#{name}_id"]) if self["#{name}_id"]
  end

  ##
  # Create a method to set the attachment
  # eg: object.image = File.open('/tmp/somefile.jpg')
  define_method("#{name}=") do |file|
    # delete the old file if it exists
    unless self["#{name}_id"].blank?
      send(:delete_attachment, name, self["#{name}_id"])
    end
    case
    when file.is_a?(Hash) && file[:tempfile]
      send(:create_attachment, name, file)
    when file.respond_to?(:read)
      send(:create_attachment, name, file)
    end
  end

  ##
  # Create a method to set the attachment for binary string.
  # eg: object.set_image(binary_string, "generated_filename.png")
  define_method("set_#{name}") do |binary, filename|
    if !binary.nil?
      send(:create_attachment_raw, name, binary, filename)
    else
      send(:delete_attachment, name, self["#{name}_id"])
    end
  end

  ##
  # Unset the attachment, queue for removal
  define_method("unset_#{name}") do
    send(:delete_attachment, name, self["#{name}_id"])
  end

  ##
  # Return the relative URL to the attachment for use with Rack::Grid
  # eg: /grid/4ba69fde8c8f369a6e000003/somefile.png
  define_method("#{name}_url") do
    _id   = self["#{name}_id"]
    _name = self["#{name}_name"]
    URI.escape(["/#{prefix}", _id, _name].join('/')) if _id && _name
  end

  ##
  # Return the relative URL to the thumbnail for use with Rack::GridThumb
  # eg: /grid/4ba69fde8c8f369a6e000003/somefile_50x.png
  define_method("#{name}_thumb") do |thumb|
    _id   = self["#{name}_id"]
    _name = self["#{name}_name"]
    _ext  = File.extname(_name)
    _base = File.basename(_name,_ext)
    _name = "#{_base}_#{thumb}#{_ext}"
    URI.escape(["/#{prefix}", _id, _name].join('/')) if _id && _name
  end
end

#attachment_typesObject

All the attachments types for this class



108
109
110
# File 'lib/grid_attachment/mongomatic.rb', line 108

def attachment_types
  @attachment_types ||= []
end

#gridObject

Accessor to Grid



102
103
104
# File 'lib/grid_attachment/mongomatic.rb', line 102

def grid
  @grid ||= Mongo::Grid.new(::Mongomatic.db)
end