Module: SequelImage

Defined in:
lib/ramaze/contrib/sequel/image.rb

Overview

Scaffold image models utilizing thumbnailing and Ramaze integration. Resizing is done by ImageScience.

Usage:

class Avatar < Sequel::Model
  IMAGE = {
    # specifies belongs_to, will create relation and foreign key

    :owner => :User,

    # Remove original and thumbnails on Avatar#destroy

    :cleanup => true,

    # Algorithm to use in ImageScience
    #
    # * resize(width, height)
    #     Resizes the image to +width+ and +height+ using a cubic-bspline
    #     filter.
    #
    # * thumbnail(size)
    #     Creates a proportional thumbnail of the image scaled so its
    #     longest edge is resized to +size+.
    #
    # * cropped_thumbnail(size)
    #     Creates a square thumbnail of the image cropping the longest edge
    #     to match the shortest edge, resizes to +size+.

    :algorithm => :thumbnail,

    # Key specifies the filename and accessors, value are arguments to the
    # algorithm

    :sizes => {
      :small => 150,
      :medium => 300,
      :large => 600
    }
  }

  # Perform the scaffold
  include SequelImage
end

Defined Under Namespace

Modules: InstanceMethods, SingletonMethods

Class Method Summary collapse

Class Method Details

.included(model) ⇒ Object



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
99
100
101
102
# File 'lib/ramaze/contrib/sequel/image.rb', line 52

def self.included(model)
  args = model::IMAGE
  set_foreign_key = args[:foreign_key] || "#{args[:owner]}_id".downcase.to_sym
  set_belongs_to  = args[:belongs_to]  ||    args[:owner].to_s.downcase.to_sym

  # Define schema
  model.set_schema do
    primary_key :id

    varchar :original # path to the original image
    varchar :mime, :size => 22 # average of /etc/mime.types

    time :created_at
    time :updated_at

    foreign_key set_foreign_key
  end

  # Define Relations
  model.belongs_to set_belongs_to

  # Define Hooks
  model.send(:hooks).clear

  model.before_create do
    generate_thumbnails
    self.created_at = Time.now
  end

  model.before_save do
    self.updated_at = Time.now
  end

  model.before_destroy do
    cleanup if conf[:cleanup]
  end

  # Define singleton methods
  model.extend(SingletonMethods)

  # Define instance methods
  model.send(:include,
             InstanceMethods,
             Ramaze::Helper::CGI,
             Ramaze::Helper::Link)

  args[:sizes].each do |size, *args|
    model.send(:define_method, size){ public_file(size) }
    model.send(:define_method, "#{size}_url"){ file(size) }
  end
end