LoginSignup
7
8

More than 5 years have passed since last update.

carrierwaveのimage_preview_inputでデフォルト画像が表示されるようカスタムする

Last updated at Posted at 2016-04-11

carrierwaveのwikiで例として提示されている image_preview_input.rb を掲題のようにカスタムしてみます。

やりたいこと

この image_preview_input.rb はアップロード済みの画像が存在する場合は、ファイルアップロードフォームの隣にアップロードした画像を表示します。

ただ、画像がアップロードされていない場合は何も表示されないので、今回は「画像がありません」といった旨の画像を表示しようという感じです。

やったこと

以下が image_preview_input.rb です。

class ImagePreviewInput < SimpleForm::Inputs::FileInput
  def input(wrapper_options = nil)
    # :preview_version is a custom attribute from :input_html hash, so you can pick custom sizes
    version = input_html_options.delete(:preview_version)
    out = ActiveSupport::SafeBuffer.new # the output buffer we're going to build
    # check if there's an uploaded file (eg: edit mode or form not saved)
    if object.send("#{attribute_name}?")
      # append preview image to output
      out << template.image_tag(object.send(attribute_name).tap {|o| break o.send(version) if version}.send('url'))
    end
    # allow multiple submissions without losing the tmp version
    out << @builder.hidden_field("#{attribute_name}_cache").html_safe
    # append file input. it will work accordingly with your simple_form wrappers
    out << @builder.file_field(attribute_name, input_html_options)
  end
end

これをこのようにカスタムします。

class ImagePreviewInput < SimpleForm::Inputs::FileInput
  def input(wrapper_options = nil)
    # input_htmlのオプションに:preview_versionがある場合、削除し値を保存
    version = input_html_options.delete(:preview_version)

    # 出力の準備
    out = ActiveSupport::SafeBuffer.new

    # attribute_nameが存在するか確認
    # 今回の場合、imageが返ってくる
    if object.send("#{attribute_name}?")
      # プレビュー画像の表示
      out << template.image_tag(object.send(attribute_name).tap {|o| break o.send(version) if version}.send('url'))
    else
      # 存在しない場合、デフォルトの画像を表示
      out << template.image_tag('default.png', size: "80x80")
    end

    # hidden_fieldとfile_fieldを追加
    out << @builder.hidden_field("#{attribute_name}_cache").html_safe
    out << @builder.file_field(attribute_name, input_html_options)
  end
end

これでアップロード済みの画像が存在しない場合は、デフォルトの画像が表示されます。

7
8
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
7
8