Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
step-to-rails-ex-paperclip
Search
ttwo32
January 09, 2017
Technology
81
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
step-to-rails-ex-paperclip
study paperclip
ttwo32
January 09, 2017
Other Decks in Technology
See All in Technology
ソフトウェアサプライチェーンの構造的リスクとコンテナ環境の保護
kyohmizu
5
770
関東Kaggler会発表資料
takoi
1
280
フィジカルAIの知識ゼロの僕でも AIを使えばここまでできた
tatsuya1970
0
100
コーチングの奥義 何もしないテクニック
jinwatanabe
0
140
Head First モブプログラミング / Head First Mobprogramming
takaking22
10
12k
RelayerというPHPのフレームワークを作った
polidog
PRO
0
110
小粒でもパワフルなJS Runtime Antjsについて
comamoca
0
120
平文パスワードはログに“残り” ── 肝心の侵入は“痕跡すら残らない”
kuroneko13
0
120
Digitization部 紹介資料
sansan33
PRO
2
7.7k
NANDでも描画したい!
nichica906
2
450
猫付きpingコマンドを自作
uyuki234
0
290
Go 1.27 の標準パッケージに uuid が入った!のでいろいろ喋る / go_127_std_go_uuid
convto
3
570
Featured
See All Featured
The Cost Of JavaScript in 2023
addyosmani
55
10k
Building Flexible Design Systems
yeseniaperezcruz
330
40k
Data-driven link building: lessons from a $708K investment (BrightonSEO talk)
szymonslowik
1
1.2k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
22k
Crafting Experiences
bethany
1
260
Measuring & Analyzing Core Web Vitals
bluesmoon
9
970
Bridging the Design Gap: How Collaborative Modelling removes blockers to flow between stakeholders and teams @FastFlow conf
baasie
0
660
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
620
SEO for Brand Visibility & Recognition
aleyda
0
4.7k
Building Adaptive Systems
keathley
44
3.2k
Practical Orchestrator
shlominoach
191
12k
Building an army of robots
kneath
306
46k
Transcript
Paperclip @ttwo32 Step-to-Rails-Expert.rb Jan.31th 2016
⾃⼰紹介 • IT系コンサル会社で社内SEやってます。 • ずっとフロントエンド中⼼にやってきた感じです。(Java歴が ⻑くてPHPは少しかじった程度) • Ruby歴は3年くらいです。(結構経ったな・・・) • holidaysっていうgemをメンテしてます。よかったら使ってく
ださいJ
Paperclipってなに? • 有名なファイルアップロード⽤のgem。⼀応file attachment librariesとのことなので画像以外も添付できるはず。 • Github => https://github.com/thoughtbot/paperclip •
8282 stars at Jan.6.2017 • 公式サイト? => https://thoughtbot.com/tools • Thoughtbot社(Factory_girlとか作った会社)なのでメンテは続きそ う。
Requirements • Ruby and Rails • Ruby >= 2.1 •
Rails >= 4.2 • imagemagick 画像処理(多分リサイズやサムネイル作成等)で必要。今回はテーマが画像な ので必須。 • File content_typeのチェックにfileコマンドの機能が必要。Unix系のOSなら特に考 慮する必要なさそう。Windows系はRubyinstallerのdevelopment-kitが必要。
Installation • include rails gems gem "paperclip” bundle install •
imagimagick • brew install imagemagick *sierraにしたせいかinstallに失敗したけどbrew updateして無事解決。
Quickstart • railsプロジェクト作成。 • rails new picture • 適当にmodel作る。 •
rails g scaffold user name:string password:string • avatarという名前でpaperclip⽤のカラムを作る。 • rails generate paperclip user avatar • paperclip⽤に以下の4カラムが追加される。 • avatar_file_name • avatar_file_size • avatar_content_type • avatar_updated_at
Quickstart • model修正 class User < ActiveRecord::Base has_attached_file :avatar, styles:
{ medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/ end • _form.html.erbの適当な位置にfile_upload⽤のフィールドを追加 <div class="field"> <%= f.label :avatar %><br> <%= f.file_field :avatar %> </div>
File upload execution • アップロードしたファイルは以下の場所に配置されている。⼀ つのファイルに対して縮⼩画像とサムネイル画像を同時に作る らしい。 public └── system
└── users └── avatars └── 000 └── 000 └── 001 ├── medium │ └── example_image1.jpg ├── original │ └── example_image1.jpg └── thumb └── example_image1.jpg なお画像以外のファイルでも imagemagickの処理は通るみたいで 同様のフォルダ構成になる。
validation • validationは3種類⽤意(size,content_type,必須)されている。 • validates_attachment_size • validates_attachment_presence • alidates_attachment_content_type •
ʻvalidates_attachmentʼを使えば複数のチェックを1カラムに まとめて設定することが可能 validates_attachment :avatar, presence: true, content_type: { content_type: "image/jpeg" }, size: { in: 0..10.kilobytes }
resizing • has_attached_fileのstyle optionで指定する class User < ActiveRecord::Base has_attached_file :avatar,
styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/ end • view側でそれぞれのサイズを取得するのは下記の通り。 • <%= image_tag @user.photo.url %> • <%= image_tag @user.photo.url(:thumb) %> • <%= image_tag @user.photo.url(:medium) %>
Prevent thumnail generation for invalid uploads. • ʼ before_post_processʼを指定すれば、paperclipの処理(サム ネイル作成処理等)の前に実⾏するチェックして処理を⽌める
ことも可能。(指定しないとinvalidになってもサムネイル作成 処理が実⾏されるらしい) (ファイルサイズの制限をする時の例) before_post_process :check_file_size def check_file_size valid? errors[:image_file_size].blank? end
Hashing • ファイル名にハッシュ値を使うことができる。 defaultではハッシュ 値を使わないので、URLにファイル名がそのまま表⽰される。 <実装> • initializerに以下のファイルを置いてサーバ再起動すればOK. # config/initializers/paperclip_defaults.rb
Paperclip::Attachment.default_options.update({ url: "/system/:class/:attachment/:id_partition/:style/:hash.:extension", hash_secret: Rails.application.secrets.secret_key_base })
最後に • 導⼊から利⽤開始まで⾮常に簡単。触ったことのない⽅は是⾮⼀度 試して⾒てください。 • ここでは取り上げていませんが、File storageとしてS3をサポート しているみたいです。ちなみにHerokuもFile storageにはS3を推奨 してるっぽいです。
https://devcenter.heroku.com/articles/paperclip-s3 • Imagemagick optionを使ってサムネイルの最適化もできるようなの で、使い⽅はかなり多岐に渡りそう。 https://github.com/thoughtbot/paperclip/wiki/Thumbnail- Generation#optimizing-thumbnails-for-the-web
参考 • https://github.com/thoughtbot/paperclip/wiki • http://qiita.com/kakipo/items/4e70428e46f60c74ea63 • http://ruby- rails.hatenadiary.com/entry/20140716/1405443484