LoginSignup
0
0

More than 5 years have passed since last update.

Railsでvueを利用しているときに本番でGCS上に配置した画像を参照するときにどうするか

Posted at

背景

開発時はローカル、本番ではGCSへコピーした画像を参照したい

やったこと

使うコンポーネントで毎回ローカルとGCSの参照を切り替えるのは面倒なので画像を扱うクラスを用意することにしました
Rails環境でRAILS_ENVにproduction,staging等が指定されGCSではバケット名が [RAILS_ENV]-assets というような名前になっている状態です
NODE_ENVはdevelopmentかproductionが指定されるのでそれを見て開発時のローカルパスを返すか、GCSのURLを返すかを判断します
画像はapp/javascript/images 以下に image-a.jpg, image-b.jpgが置いてある前提です

config/webpack/environment.js
...

environment.config.merge({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, '..', '..', 'app/javascript')
    }
  }
})

module.exports = environment
image.js
'use strict'
import imageA from '@/images/image-a'
import imageB from '@/images/image-b'

const GCS_DOMAIN = 'storage.googleapis.com'
const BUCKET = `${process.env.RAILS_ENV}-assets`
const PROTOCOL = 'https'

class Image {
  static sources = {
    imageA: imageA,
    imageB: imageB
  }

  constructor () {
    this.host = ""
    if (process.env.NODE_ENV === 'production')
      this.host = `${PROTOCOL}://${BUCKET}.${GCS_DOMAIN}`
  }

  /**
   * 画像のパスを取得
   * @returns {String}
   */
  getSrc (key) {
    return `${this.host}${Image.sources[key]}`
  }
}

export default new Image
Image.vue
<template lang="pug">
img(:src="src")
</template>

<script>
import image from './image'

export default {
  data () {
    src: image.getSrc('imageA')
  }
}
</script>
0
0
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
0
0