LoginSignup
11
10

More than 5 years have passed since last update.

paperclipでweb上の動画を保存する!

Last updated at Posted at 2016-01-06

paperclipでweb上の動画を保存する方法

まずは下記をGemfileに記述し、bundle installを実行してください

Gemfile
gem 'paperclip'
$ bundle install

Movieモデルを作成します

$ rails g model movie 

migrationファイルは下記のように記述

yyyymmddhhmmss_create_movies.rb
class CreateMovies < ActiveRecord::Migration
  def change
    create_table :movies do |t|
      t.attachment :videofile
      t.timestamps null: false
    end
  end
end

attachmentは、paperclipで定義されており、ファイル情報を保持するために複数カラムを追加してくれます。

migrationを実行

$ rake db:migrate

モデルは下記のように記述

movie.rb
class Movie < ActiveRecord::Base
  has_attached_file :videofile,
    path: "#{Rails.root}/public/system/:class/:id.:extension",
    url: "/system/:class/:id.:extension"
  validates_attachment_content_type :videofile, content_type: ["video/mp4"]
end

validates_attachment_content_typeは今回mp4を対象にしています。

保存処理を実行する際の記述

movie_controller.rb
  def save_movie(url)
    movie = Movie.new
    # web上から動画を取得
    open(url, 'User-Agent' => 'Your User Agent') do |videofile|
      movie.videofile = videofile
    end
    movie.save!
  end

openで指定したurlの動画を取得します。
エラー処理などを一切省いていますが、これでweb上から動画を取得して保存できます。

保存した動画を呼び出すには、viewで下記を記述してください。

movie.html.er
  <div class="movie">
    <video autoplay loop width="420" height="420">
      <source src="<%= @movie.videofile %>">
      <p>動画を再生するにはvideoタグをサポートしたブラウザが必要です。</p>
    </video>
  </div>

以上で完了です。

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10