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 many_to_one, 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
# 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_many_to_one  = args[:many_to_one] ||    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.many_to_one set_many_to_one

  # Define Hooks
  model.before_create :generate_thumbnails do
    generate_thumbnails
    self.created_at = Time.now
  end

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

  model.before_destroy :cleanup 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