Module: Editmode::ActionViewExtensions::EditmodeHelper

Includes:
Helper
Included in:
Editmode, ChunkValue
Defined in:
lib/editmode/action_view_extensions/editmode_helper.rb

Instance Method Summary collapse

Methods included from Helper

#e, #parse_arguments, #render_custom_field_raw

Instance Method Details

#api_root_urlObject



13
14
15
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 13

def api_root_url
  ENV["EDITMODE_OVERRIDE_API_URL"] || "https://api.editmode.com"
end

#api_versionObject



9
10
11
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 9

def api_version
  # Todo Add Header Version
end

#chunk_collection(collection_identifier, **options, &block) ⇒ Object Also known as: c



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 17

def chunk_collection(collection_identifier, **options, &block)
  branch_params = params[:em_branch_id].present? ? "branch_id=#{params[:em_branch_id]}" : ""
  branch_id = params[:em_branch_id].presence
  tags = options[:tags].presence || []
  limit = options[:limit].presence

  parent_class = options[:class] || ""
  item_class = options[:item_class] || ""
  
  begin 
    url_params = { 
      :collection_identifier => collection_identifier,
      :branch_id => branch_id,
      :limit => limit,
      :tags => tags
    }.to_query

    url = URI(api_root_url)
    url.path = '/chunks'
    url.query = url_params

    cache_identifier = "collection_#{collection_identifier}#{branch_id}#{limit}#{tags.join}"
    cached_content_present = Rails.cache.exist?(cache_identifier)
    
    if !cached_content_present
      response = HTTParty.get(url)
      response_received = true if response.code == 200
    end
    
    if !cached_content_present && !response_received
      raise "No response received"
    else

      chunks = Rails.cache.fetch(cache_identifier) do  
        response['chunks']
      end

      if chunks.any?
         :div, class: "chunks-collection-wrapper #{parent_class}", data: {chunk_collection_identifier: collection_identifier} do
          chunks.each do |chunk|
            @custom_field_chunk = chunk
            concat((:div, class: "chunks-collection-item--wrapper #{item_class}") do
              yield
            end)
          end

          # Placeholder element for new collection item
          @custom_field_chunk = chunks.first.merge!({placeholder: true})
          concat((:div, class: "chunks-hide chunks-col-placeholder-wrapper") do
            yield
          end)
        end 
      else
        (:span, "&nbsp".html_safe)
      end
    end
  rescue => error
    puts error 
    return []
  end
end

#chunk_display(label, identifier, options = {}, &block) ⇒ Object Also known as: chunk



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 152

def chunk_display(label, identifier, options = {}, &block)
  branch_id = params[:em_branch_id]
  # This method should never show an error. 
  # If anything goes wrong fetching content
  # We should just show blank content, not
  # prevent the page from loading.
  begin
    branch_params = branch_id.present? ? "branch_id=#{branch_id}" : ""
    field = options[:field].presence || ""          
    cache_identifier = "chunk_#{identifier}#{branch_id}#{field}"
    url = "#{api_root_url}/chunks/#{identifier}?project_id=#{Editmode.project_id}&#{branch_params}"
    cached_content_present = Rails.cache.exist?(cache_identifier)
    parent_identifier = identifier if field.present?
    if !cached_content_present
      response = HTTParty.get(url)
      response_received = true if response.code == 200
    end

    if !cached_content_present && !response_received
      raise "No response received"
    else
      if field.present? && response.present?
        field_content = response["content"].detect {|f| f["custom_field_identifier"].downcase == field.downcase || f["custom_field_name"].downcase == field.downcase }
        if field_content
          content = field_content["content"]
          type = field_content["chunk_type"]
          identifier = Rails.cache.fetch("#{cache_identifier}_field_identifier") do
            field_content["identifier"]
          end
        end
      end

      variable_fallbacks = Rails.cache.fetch("#{cache_identifier}_variables") do
        response['variable_fallbacks'].presence || {}
      end

      chunk_content = Rails.cache.fetch(cache_identifier) do  
        content.presence || response["content"]
      end

      chunk_type = Rails.cache.fetch("#{cache_identifier}_type") do  
        type.presence || response['chunk_type']
      end

      identifier = Rails.cache.fetch("#{cache_identifier}_field_identifier") do
        identifier
      end

      options[:variable_fallbacks] = variable_fallbacks
      options[:variable_values] = options[:variables].presence || {}
      
      options[:cache_identifier] =  parent_identifier.presence || identifier
      
      render_chunk_content(identifier,chunk_content,chunk_type, options)
    end

  rescue => error
    # Show fallback content by default
    return ("em-span", &block) if block_given?
    # Otherwise show a span with no content to 
    # maintain layout
    ("em-span", "&nbsp".html_safe) 
  end
end

#chunk_field_value(parent_chunk_object, custom_field_identifier, options = {}) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 80

def chunk_field_value(parent_chunk_object, custom_field_identifier, options = {})
  begin 
    chunk_identifier = parent_chunk_object["identifier"]
    custom_field_item = parent_chunk_object["content"].detect do |f|
      f["custom_field_identifier"].try(:downcase) == custom_field_identifier.try(:downcase)  || f["custom_field_name"].try(:downcase)  == custom_field_identifier.try(:downcase)
    end

    options[:field] = custom_field_identifier
    
    if parent_chunk_object[:placeholder]
      custom_field_item["identifier"] = ""
      custom_field_item["content"] = ""
    end

    if custom_field_item.present?
      render_chunk_content(
        custom_field_item["identifier"],
        custom_field_item["content"],
        custom_field_item["chunk_type"],
        { parent_identifier: chunk_identifier, custom_field_identifier:  custom_field_identifier}.merge(options)
      )
    end
  rescue => errors
    puts errors
    (:span, "&nbsp".html_safe) 
  end
end

#no_response_received(id = "") ⇒ Object



256
257
258
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 256

def no_response_received(id = "")
  "Sorry, we can't find a chunk using this identifier: \"#{id}\". This can happen if you've deleted a chunk on editmode.com or if your local cache is out of date. If it persists, try running Rails.cache clear."
end

#render_chunk(identifier, *args, &block) ⇒ Object Also known as: E



227
228
229
230
231
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 227

def render_chunk(identifier, *args, &block)
  field, options = parse_arguments(args)
  options[:field] = field
  chunk_display('label', identifier, options, &block)
end

#render_chunk_content(chunk_identifier, chunk_content, chunk_type, options = {}) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 108

def render_chunk_content(chunk_identifier, chunk_content, chunk_type,options = {})

  begin 
    # Always sanitize the content!!
    chunk_content = ActionController::Base.helpers.sanitize(chunk_content) unless chunk_type == 'rich_text'
    chunk_content = variable_parse!(chunk_content, options[:variable_fallbacks], options[:variable_values])

    css_class = options[:class]
    cache_id = options[:cache_identifier]

    if chunk_type == "image"
      display_type = "image"
    else 
      display_type = options[:display_type] || "span"
    end

    chunk_data = { :chunk => chunk_identifier, :chunk_editable => false, :chunk_type => chunk_type }

    chunk_data.merge!({parent_identifier: options[:parent_identifier]}) if options[:parent_identifier].present?
    chunk_data.merge!({custom_field_identifier: options[:custom_field_identifier]}) if options[:custom_field_identifier].present?
    chunk_data.merge!({chunk_cache_id: cache_id}) if cache_id.present?

    case display_type
    when "span"
      if chunk_type == "rich_text"
        content = ("em-span", :class => "editmode-richtext-editor #{css_class}", :data => chunk_data.merge!({:chunk_editable => true}) ) do
          chunk_content.html_safe
        end
      else
        ("em-span", :class => css_class, :data => chunk_data.merge!({:chunk_editable => true}) ) do
          chunk_content.html_safe
        end
      end
    when "image"
      chunk_content = chunk_content.blank? || chunk_content == "/images/original/missing.png" ? 'https://www.editmode.com/upload.png' : chunk_content
      image_tag(chunk_content, :data => chunk_data, :class => css_class) 
    end
  rescue => errors
    puts errors
    ("em-span", "&nbsp".html_safe) 
  end

end

#render_custom_field(field_name, options = {}) ⇒ Object Also known as: F



219
220
221
222
223
224
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 219

def render_custom_field(field_name, options={})
  options[:variable_fallbacks] = @custom_field_chunk["variable_fallbacks"] || {}
  options[:variable_values] = options[:variables] || {}
  
  chunk_field_value(@custom_field_chunk, field_name, options)
end

#require_field_idObject



260
261
262
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 260

def require_field_id
  "Field ID or Field Name is required to retrieve a collection item"
end

#variable_parse!(content, variables = {}, values = {}, raw = false) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/editmode/action_view_extensions/editmode_helper.rb', line 235

def variable_parse!(content, variables = {}, values = {}, raw = false)
  tokens = content.scan(/\{{(.*?)\}}/)
  if tokens.any?
    tokens.flatten! 
    tokens.each do |token|
      token_value = values[token.to_sym] || variables[token] || ""
      sanitized_value = ActionController::Base.helpers.sanitize(token_value)

      unless raw
        sanitized_value = ("em-var", :data => {chunk_variable: token, chunk_variable_value: sanitized_value}) do
          sanitized_value
        end
      end
      
      content.gsub!("{{#{token}}}", sanitized_value)
    end
  end

  content
end