Class: Workarea::Storefront::ContentBlockViewModel

Inherits:
ApplicationViewModel
  • Object
show all
Defined in:
app/view_models/workarea/storefront/content_block_view_model.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.wrap(model, options = {}) ⇒ Object



4
5
6
7
8
9
# File 'app/view_models/workarea/storefront/content_block_view_model.rb', line 4

def self.wrap(model, options = {})
  return model.map { |m| wrap(m, options) } if model.is_a?(Enumerable)
  model.type.view_model.constantize.new(model, options)
rescue NameError
  new(model, options)
end

Instance Method Details

#asset_alt_textObject



52
53
54
55
56
57
58
59
60
# File 'app/view_models/workarea/storefront/content_block_view_model.rb', line 52

def asset_alt_text
  @asset_alt_texts ||= model.type
    .fields
    .select { |f| f.options[:alt_field].present? }
    .each_with_object({}) do |field, memo|
      key = field.options[:alt_field].systemize.to_sym
      memo[key] = find_asset(model.data[field.slug])&.alt_text
    end
end

#assetsObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'app/view_models/workarea/storefront/content_block_view_model.rb', line 33

def assets
  @assets ||= begin
    asset_ids = model
      .type
      .fields
      .select { |field, _memo| field.type == :asset }
      .map { |field| model.data[field.slug] }
      .reject(&:blank?)
      .map(&:to_s)

    assets = Content::Asset.in(id: asset_ids)

    asset_ids.each_with_object({}) do |id, memo|
      memo[id] = assets.detect { |a| a.id.to_s == id } ||
                 Content::Asset.image_placeholder
    end
  end
end

#find_asset(id) ⇒ Object



24
25
26
27
28
29
30
31
# File 'app/view_models/workarea/storefront/content_block_view_model.rb', line 24

def find_asset(id)
  return Content::Asset.image_placeholder if id.blank?
  return assets[id.to_s] if assets[id.to_s].present?

  assets[id.to_s] = Content::Asset.find(id)
rescue Mongoid::Errors::DocumentNotFound
  assets[id.to_s] = Content::Asset.image_placeholder
end

#localsObject



15
16
17
18
19
20
21
22
# File 'app/view_models/workarea/storefront/content_block_view_model.rb', line 15

def locals
  @locals ||= model
    .data
    .merge(hidden_breakpoints: model.hidden_breakpoints, view_model: self)
    .merge(asset_alt_text) do |_, block_alt, asset_alt|
      block_alt.presence || asset_alt
    end
end

#partialObject



11
12
13
# File 'app/view_models/workarea/storefront/content_block_view_model.rb', line 11

def partial
  "workarea/storefront/content_blocks/#{model.type.slug}"
end

#seriesObject



62
63
64
# File 'app/view_models/workarea/storefront/content_block_view_model.rb', line 62

def series
  @series ||= options[:base].try(:series) || generate_series
end