Class: Goldencobra::Article

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
Goldencobra::ArticleConcerns::MetaTag
Defined in:
app/models/goldencobra/article.rb

Constant Summary collapse

LiquidParser =

extend FriendlyId

{}
SortOptions =
["Created_at", "Updated_at", "Random", "Alphabetically", "GlobalSortID"]
DynamicRedirectOptions =
[[:false,"deaktiviert"],[:latest,"neuester Untereintrag"], [:oldest, "ältester Untereintrag"]]
DisplayIndexTypes =
[["Einzelseiten und Übersichtsseiten", "all"], ["Einzelseiten", "show"],["Übersichtsseiten", "index"]]
ImportDataFunctions =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object

dynamic method for an object to make the article respond to it like article.object



247
248
249
250
251
252
253
254
255
256
257
# File 'app/models/goldencobra/article.rb', line 247

def method_missing(meth, *args, &block)
  if meth.to_s.split(".").first == self.get_related_object.class.name.downcase
    if meth.to_s.split(".").count == 1
      self.get_related_object
    else
      self.get_related_object.send(meth.to_s.split(".").last)
    end
  else
    super
  end
end

Instance Attribute Details

#create_redirectionObject

Returns the value of attribute create_redirection.



63
64
65
# File 'app/models/goldencobra/article.rb', line 63

def create_redirection
  @create_redirection
end

#hint_labelObject

Returns the value of attribute hint_label.



63
64
65
# File 'app/models/goldencobra/article.rb', line 63

def hint_label
  @hint_label
end

#manual_article_sortObject

Returns the value of attribute manual_article_sort.



63
64
65
# File 'app/models/goldencobra/article.rb', line 63

def manual_article_sort
  @manual_article_sort
end

Class Method Details

.article_types_for_searchObject



838
839
840
841
842
843
844
845
846
847
# File 'app/models/goldencobra/article.rb', line 838

def self.article_types_for_search
  results = []
  path_to_articletypes = File.join(::Rails.root, "app", "views", "articletypes")
  if Dir.exist?(path_to_articletypes)
    Dir.foreach(path_to_articletypes) do |name|
      results << name.capitalize unless name.include?(".")
    end
  end
  return results
end

.article_types_for_selectObject



821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'app/models/goldencobra/article.rb', line 821

def self.article_types_for_select
  results = []
  path_to_articletypes = File.join(::Rails.root, "app", "views", "articletypes")
  if Dir.exist?(path_to_articletypes)
    Dir.foreach(path_to_articletypes) do |name|
      file_name_path = File.join(path_to_articletypes,name)
      if File.directory?(file_name_path)
        Dir.foreach(file_name_path) do |sub_name|
          file_name = [name.titleize.gsub(' ',''), sub_name.gsub('_','').titleize].join(" ") if File.exist?(File.join(file_name_path,sub_name)) && (sub_name =~ /^_(?!edit).*/) == 0
          results << file_name.split(".").first if file_name.present?
        end
      end
    end
  end
  return results
end

.articles_for_index_selecetionObject



553
554
555
556
557
558
559
560
561
562
563
564
# File 'app/models/goldencobra/article.rb', line 553

def self.articles_for_index_selecetion
  cache_key ||= [
    "indexarticlesselect",
    Goldencobra::Article.all.pluck(:id, :ancestry, :url_name)
  ]

  Rails.cache.fetch(cache_key) do
    Goldencobra::Article.select([:id, :ancestry, :url_name]).map do
      |a| [a.parent_path, a.id]
    end.sort
  end
end

.articletype_for_index(current_article) ⇒ Object

scope for index articles, display show-articles, index-articles or both articletypes



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'app/models/goldencobra/article.rb', line 418

def self.articletype_for_index(current_article)
  # Wenn alle Artikeltypen angezeigt werden sollen
  if current_article.display_index_articletypes == "all"
    if current_article.display_index_types == "show"
      where("article_type LIKE '% Show' ")
    elsif current_article.display_index_types == "index"
      where("article_type LIKE '% Index' ")
    else
      where("article_type LIKE '% Show' OR article_type LIKE '% Index' ")
    end
  else
    # Wenn NUR Artikel von EINEM bestimmten Artkeltypen angezeigt werden sollen
    if current_article.display_index_types == "show"
      articletype("#{current_article.display_index_articletypes} Show")
    elsif current_article.display_index_types == "index"
      articletype("#{current_article.display_index_articletypes} Index")
    else
      where("article_type = '#{current_article.display_index_articletypes} Show' OR article_type = '#{current_article.display_index_articletypes} Index'")
    end
  end
end

.init_image_methodsObject



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'app/models/goldencobra/article.rb', line 196

def self.init_image_methods
  if ActiveRecord::Base.connection.table_exists?("goldencobra_settings")
    Goldencobra::Setting.for_key("goldencobra.article.image_positions").to_s.split(",").map(&:strip).each do |image_type|
      define_method "image_#{image_type.underscore}" do
        image(image_type, "original")
      end
      define_method "image_alt_#{image_type.underscore}" do
        selected_images = article_images.where(position: image_type)
        return "" if selected_images.none? || selected_images.first.image.blank?
        selected_images.first.image.alt_text || selected_images.first.image.image_file_name
      end
      if ActiveRecord::Base.connection.table_exists?("goldencobra_uploads") && Goldencobra::Upload.respond_to?(:attachment_definitions)
        Goldencobra::Upload.attachment_definitions[:image][:styles].keys.each do |style_name|
          define_method "image_#{image_type.underscore}_#{style_name}" do
            image(image_type, style_name)
          end
        end
      end
    end
  end
end

.load_liquid_methods(options = {}) ⇒ Object



803
804
805
806
807
# File 'app/models/goldencobra/article.rb', line 803

def self.load_liquid_methods(options = {})
  Goldencobra::Article::LiquidParser["location"] = options.fetch(:location, nil)
  Goldencobra::Article::LiquidParser["current_article"] = options.fetch(:article, nil)
  Goldencobra::Article::LiquidParser["url_params"] = options.fetch(:params, nil)
end

.recent(count) ⇒ Object



809
810
811
# File 'app/models/goldencobra/article.rb', line 809

def self.recent(count)
  Goldencobra::Article.where("title IS NOT NULL").order("created_at DESC").limit(count)
end

.recreate_cacheObject



813
814
815
816
817
818
819
# File 'app/models/goldencobra/article.rb', line 813

def self.recreate_cache
  if RUBY_VERSION.to_f >= 1.9
    ArticlesCacheWorker.perform_async
  else
    Goldencobra::Article.active.each(&:touch)
  end
end

.search_by_url(url) ⇒ Object

************************** ************************** URL and Redirection Methods ************************** **************************



746
747
748
749
750
751
752
753
754
# File 'app/models/goldencobra/article.rb', line 746

def self.search_by_url(url)
  article = nil
  articles = Goldencobra::Article.where(url_name: url.split("/").last.to_s.split(".").first)
  article_path = "/#{url.split('.').first}"
  if articles.count > 0
    article = articles.select { |a| a.public_url(false) == article_path }.first
  end
  return article
end

.simple_search(q) ⇒ Object



855
856
857
858
859
860
861
862
863
864
865
866
867
868
# File 'app/models/goldencobra/article.rb', line 855

def self.simple_search(q)
  active.search(title_or_subtitle_or_url_name_or_content_or_summary_or_teaser_contains: q).relation.map do |article|
    {
      id: article.id,
      absolute_public_url: article.absolute_public_url,
      title: article ? article.title : '',
      teaser: article ? article.teaser : '',
      article_type: article.article_type,
      updated_at: article.updated_at,
      parent_title: article.parent ? article.parent.title ? article.parent.title : '' : '',
      ancestry: article.ancestry ? article.ancestry : ''
    }
  end
end

.state_attributes_for_selectObject

************************** ************************** Class Methods ************************** **************************



797
798
799
800
801
# File 'app/models/goldencobra/article.rb', line 797

def self.state_attributes_for_select
  states.map do |s, _|
    [I18n.t("activerecord.attributes.#{model_name.i18n_key}.states.#{s}"), s]
  end
end

.templates_for_selectObject



849
850
851
852
853
# File 'app/models/goldencobra/article.rb', line 849

def self.templates_for_select
  Dir.glob(File.join(::Rails.root, "app", "views", "layouts", "*.html.erb"))
     .map { |a| File.basename(a, ".html.erb") }
     .delete_if { |a| a =~ /^_/ }
end

Instance Method Details

#absolute_base_urlObject



782
783
784
# File 'app/models/goldencobra/article.rb', line 782

def absolute_base_url
  Goldencobra::Url.to_s
end

#absolute_public_urlObject



787
788
789
# File 'app/models/goldencobra/article.rb', line 787

def absolute_public_url
  "#{absolute_base_url}#{public_url}"
end

#active?Boolean

************************** ************************** Instance Methods ************************** **************************

Returns:

  • (Boolean)


166
167
168
# File 'app/models/goldencobra/article.rb', line 166

def active?
  self.active && self.active_since < Time.now.utc
end

#article_for_index_limitObject



358
359
360
361
362
363
364
# File 'app/models/goldencobra/article.rb', line 358

def article_for_index_limit
  if self.article_for_index_count.to_i <= 0
    return 1000
  else
    self.article_for_index_count.to_i
  end
end

#article_type_for_searchObject

Liefert Kategorienenamen für sie Suche unabhängig ob Die Seite eine show oder indexseite ist



324
325
326
327
328
329
330
# File 'app/models/goldencobra/article.rb', line 324

def article_type_for_search
  if self.article_type.present?
    self.article_type.split(" ")[0..-2].join("")
  else
    "Article"
  end
end

#article_type_form_fileObject

returns article type name without index/show



312
313
314
315
316
# File 'app/models/goldencobra/article.rb', line 312

def article_type_form_file
  if self.article_type.present?
    self.article_type.split(" ")[0..-2].join("")
  end
end

#article_type_xml_fieldsObject

Returns a special article_typs customs rss fields as xml



290
291
292
293
294
295
# File 'app/models/goldencobra/article.rb', line 290

def article_type_xml_fields
  related_object = self.get_related_object
  if related_object && related_object.respond_to?(:custom_rss_fields)
    related_object.custom_rss_fields
  end
end

#authorObject



406
407
408
# File 'app/models/goldencobra/article.rb', line 406

def author
  self.try(:authors).try(:first)
end


344
345
346
347
348
349
350
# File 'app/models/goldencobra/article.rb', line 344

def breadcrumb_name
  if self.breadcrumb.present?
    return self.breadcrumb
  else
    return self.title
  end
end

#cleanup_redirectionsObject



594
595
596
# File 'app/models/goldencobra/article.rb', line 594

def cleanup_redirections
  Goldencobra::Redirector.where(source_url: self.absolute_public_url).destroy_all
end

#comments_of_subarticlesObject



454
455
456
# File 'app/models/goldencobra/article.rb', line 454

def comments_of_subarticles
  Goldencobra::Comment.where("article_id in (?)", self.subtree_ids)
end

#complete_jsonObject



402
403
404
# File 'app/models/goldencobra/article.rb', line 402

def complete_json

end

#date_of_last_modified_childObject



298
299
300
301
302
303
304
305
306
307
308
# File 'app/models/goldencobra/article.rb', line 298

def date_of_last_modified_child
  if self.children.length > 0
    if self.children.order("updated_at DESC").first.updated_at.utc > self.updated_at.utc
      self.children.order("updated_at DESC").first.updated_at.utc
    else
      self.updated_at.utc
    end
  else
    self.updated_at.utc
  end
end

#filter_with_permissions(list, current_operator) ⇒ Object

Methode filtert die @list_of_articles. Rückgabewert: Ein Array all der Artikel, die der operator lesen darf.



262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'app/models/goldencobra/article.rb', line 262

def filter_with_permissions(list, current_operator)
  if current_operator && current_operator.respond_to?(:has_role?) && current_operator.has_role?(Goldencobra::Setting.for_key("goldencobra.article.preview.roles").split(",").map{|a| a.strip})
    return list
  else
    a = Ability.new(current_operator)
    new_list = []
    list.each do |article|
      if a.can?(:read, article)
        new_list << article.id
      end
    end
  end
  return list.where('goldencobra_articles.id in (?)', new_list)
end


458
459
460
461
462
463
464
# File 'app/models/goldencobra/article.rb', line 458

def find_related_subarticle
  if self.dynamic_redirection == "latest"
    self.descendants.order("id DESC").first
  else
    self.descendants.order("id ASC").first
  end
end

gets the related object by article_type



236
237
238
239
240
241
242
243
244
# File 'app/models/goldencobra/article.rb', line 236

def get_related_object
  if self.article_type.present? && self.article_type_form_file.present? &&
      self.respond_to?(self.article_type_form_file.underscore.parameterize.downcase)

    return self.send(self.article_type_form_file.underscore.parameterize.downcase)
  else
    return nil
  end
end

#get_url_from_pathObject



650
651
652
# File 'app/models/goldencobra/article.rb', line 650

def get_url_from_path
  "/#{self.path.select([:ancestry, :url_name, :startpage, :id]).map{|a| a.url_name if !a.startpage}.compact.join("/")}"
end

#has_childrenObject



181
182
183
# File 'app/models/goldencobra/article.rb', line 181

def has_children
  self.has_children?
end

#image(position = "standard", size = "original") ⇒ Object



218
219
220
221
222
223
224
225
# File 'app/models/goldencobra/article.rb', line 218

def image(position = "standard", size = "original")
  selected_images = self.article_images.where(position: position)
  if selected_images.any? && selected_images.first.image && selected_images.first.image.image
    return selected_images.first.image.image.url(size.to_sym)
  else
    return ""
  end
end

#index_articles(current_operator = nil, user_frontend_tags = nil) ⇒ Object



467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'app/models/goldencobra/article.rb', line 467

def index_articles(current_operator=nil, user_frontend_tags=nil)
  return Goldencobra::Article.none unless display_index_articles

  if self.article_for_index_id.blank?
    # Index aller Artikel anzeigen
    @list_of_articles = Goldencobra::Article.active.articletype_for_index(self)
  else
    # Index aller Artikel anzeigen, die Kinder sind von einem Bestimmten artikel
    parent_article = Goldencobra::Article.where(id: self.article_for_index_id).select(:id, :ancestry).first
    if parent_article.present?
      @list_of_articles = parent_article.descendants.active.articletype_for_index(self)
      # Wenn nicht alle Ebenen unterhalb des gewählten Baumes angezeigt werden sollen
      unless self.index_of_articles_descendents_depth == "all"
        current_depth = parent_article.depth
        @list_of_articles = @list_of_articles.to_depth(current_depth + self.index_of_articles_descendents_depth.to_i)
      end
    else
      @list_of_articles = Goldencobra::Article.active.articletype_for_index(self)
    end
  end

  # include related models
  if self.respond_to?(self.article_type_form_file.underscore.parameterize.downcase)
    @list_of_articles = @list_of_articles.includes("#{self.article_type_form_file.underscore.parameterize.downcase}")
  end

  # get articles with tag
  if self.index_of_articles_tagged_with.present?
    @list_of_articles = @list_of_articles.tagged_with(self.index_of_articles_tagged_with.split(",").map(&:strip),
                                                      on: :tags,
                                                      any: true)
  end

  # get articles without tag
  if self.not_tagged_with.present?
    @list_of_articles = @list_of_articles.tagged_with(self.not_tagged_with.split(",").map(&:strip),
                                                      exclude: true,
                                                      on: :tags)
  end

  # get_articles_by_frontend_tags
  if user_frontend_tags.present?
    @list_of_articles = @list_of_articles.tagged_with(user_frontend_tags, on: :frontend_tags, any: true)
  end

  # filter with permissions
  @list_of_articles = filter_with_permissions(@list_of_articles, current_operator)

  # sort list of articles
  if sort_order.present?
    if sort_order == "Random"
      @list_of_articles = @list_of_articles.flatten.shuffle
    elsif sort_order == "Alphabetically"
      @list_of_articles = @list_of_articles.flatten.sort_by do |article|
        [article.title.downcase, article.title]
      end
    elsif sort_order == "GlobalSortID"
      @list_of_articles = @list_of_articles.flatten.sort_by do |article|
        article.try(:global_sorting_id).to_i
      end
    elsif respond_to?(sort_order.downcase)
      sorter = sort_order.downcase.to_sym
      @list_of_articles = @list_of_articles.flatten.sort_by do |article|
        article.respond_to?(sorter) ? article.send(sorter) : article
      end
    elsif sort_order.include?(".")
      sorter = sort_order.downcase
      @unsortable = @list_of_articles.flatten.select { |a| !a.respond_to_all?(sorter) }
      @list_of_articles = @list_of_articles.flatten.delete_if { |a| !a.respond_to_all?(sorter) }
      @list_of_articles = @list_of_articles.sort_by { |a| eval("a.#{sorter}") }
      if @unsortable.count > 0
        @list_of_articles = @unsortable + @list_of_articles
        @list_of_articles = @list_of_articles.flatten
      end
    end
    if reverse_sort
      @list_of_articles = @list_of_articles.reverse
    end
  end
  if sorter_limit && sorter_limit > 0
    @list_of_articles = @list_of_articles[0..sorter_limit - 1]
  end

  @list_of_articles
end

#is_startpage?Boolean

Returns:

  • (Boolean)


375
376
377
# File 'app/models/goldencobra/article.rb', line 375

def is_startpage?
  self.startpage
end

#kind_of_article_typeObject

returns index/show without article type name



319
320
321
# File 'app/models/goldencobra/article.rb', line 319

def kind_of_article_type
  self.article_type.present? ? self.article_type.split(" ").last : ""
end


170
171
172
173
174
175
176
177
178
179
# File 'app/models/goldencobra/article.rb', line 170

def link_checker
  old_result = {}
  self.link_checks.each do |lc|
    old_result[lc.target_link] = { "response_code"  => lc.response_code,
                                   "response_time"  => lc.response_time,
                                   "response_error" => lc.response_error,
                                   "position"       => lc.position }
  end
  return old_result
end

#linked_menuesObject



398
399
400
# File 'app/models/goldencobra/article.rb', line 398

def linked_menues
  Goldencobra::Menue.where(target: self.public_url)
end

#mark_as_startpage!Object



366
367
368
369
370
371
372
373
# File 'app/models/goldencobra/article.rb', line 366

def mark_as_startpage!
  Goldencobra::Article.startpage.each do |a|
    a.startpage = false
    a.save
  end
  self.startpage = true
  self.save
end

#metatag(name) ⇒ Object



379
380
381
# File 'app/models/goldencobra/article.rb', line 379

def metatag(name)
  warn "Deprecated method metatag(name). Will be removed in GC 2.1"
end

#notification_event_createObject



689
690
691
# File 'app/models/goldencobra/article.rb', line 689

def notification_event_create
  ActiveSupport::Notifications.instrument("goldencobra.article.created", article_id: id)
end

#notification_event_updateObject



693
694
695
# File 'app/models/goldencobra/article.rb', line 693

def notification_event_update
  ActiveSupport::Notifications.instrument("goldencobra.article.updated", article_id: id)
end

#parent_pathObject



756
757
758
# File 'app/models/goldencobra/article.rb', line 756

def parent_path
  self.path.map(&:url_name).join("/")
end


665
666
667
668
669
# File 'app/models/goldencobra/article.rb', line 665

def parse_image_gallery_tags
  if self.respond_to?(:image_gallery_tags)
    self.image_gallery_tags = self.image_gallery_tags.compact.delete_if{|a| a.blank?}.join(",") if self.image_gallery_tags.class == Array
  end
end

#parsed_titleObject

Das ist der Titel, der verwendet wird, wenn daraus ein Menüpunkt erstellt werden soll. der menue.title hat folgende vorgaben: validates_format_of :title, with: /^[wd?.'!s&üÜöÖäÄß-:,"]+$/



191
192
193
# File 'app/models/goldencobra/article.rb', line 191

def parsed_title
  self.title.to_s.gsub("/", " ")
end

#public_teaserObject



352
353
354
355
356
# File 'app/models/goldencobra/article.rb', line 352

def public_teaser
  return self.teaser if self.teaser.present?
  return self.summary if self.teaser.blank? && self.summary.present?
  return self.content[0..200] if self.teaser.blank? && self.summary.blank?
end

#public_url(with_prefix = true) ⇒ Object



760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# File 'app/models/goldencobra/article.rb', line 760

def public_url(with_prefix = true)
  if self.startpage
    if with_prefix
      return "#{Goldencobra::Domain.current.try(:url_prefix)}/"
    else
      return "/"
    end
  else

    #url_path in der Datenbank als string speichern und beim update von ancestry neu berechnen... ansonsten den urlpath aus dem string holen statt jedesmal über alle eltern zu iterieren
    if self.url_path.blank? || self.url_path_changed? || self.url_name_changed? || self.ancestry_changed? || self.ancestors.map{ |a| a.url_path_changed? }
      a_url = self.get_url_from_path
    else
      a_url = self.url_path
    end

    return "#{Goldencobra::Domain.current.try(:url_prefix)}#{a_url}" if with_prefix

    a_url
  end
end

#published_atObject

Datum für den RSS reader, Datum ist created_at es sei denn ein Articletype hat ein published_at definiert



385
386
387
388
389
390
391
392
393
394
395
396
# File 'app/models/goldencobra/article.rb', line 385

def published_at
  if self.article_type.present? && self.article_type_form_file.present? && self.respond_to?(self.article_type_form_file.underscore.parameterize.downcase)
    related_object = self.send(self.article_type_form_file.underscore.parameterize.downcase)
    if related_object && related_object.respond_to?(:published_at)
      related_object.published_at
    else
      self.created_at
    end
  else
    self.created_at
  end
end

#remove_html_tags(text) ⇒ Object

helper um links zu entfernen in text



672
673
674
# File 'app/models/goldencobra/article.rb', line 672

def remove_html_tags(text)
  text.gsub(/<[^<]+?>/, "")
end

#render_html(layoutfile = "application", localparams = {}) ⇒ Object



440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'app/models/goldencobra/article.rb', line 440

def render_html(layoutfile="application", localparams={})
  av = ActionView::Base.new(ActionController::Base.view_paths + ["#{::Goldencobra::Engine.root}/app/views/goldencobra/articles/"])
  av.request = ActionDispatch::Request.new(Rack::MockRequest.env_for(self.public_url))
  av.request["format"] = "text/html"
  av.controller = Goldencobra::ArticlesController.new
  av.controller.request = av.request
  if localparams.present? && localparams[:params].present?
    av.params.merge!(localparams[:params])
  end
  av.assign({article: self})
  html_to_render = av.render(template: "/goldencobra/articles/show.html.erb", layout: "layouts/#{layoutfile}", locals: localparams, content_type: "text/html" )
  return html_to_render
end

#respond_to_all?(method_name) ⇒ Boolean

Returns:

  • (Boolean)


227
228
229
230
231
232
233
# File 'app/models/goldencobra/article.rb', line 227

def respond_to_all?(method_name)
  begin
    return eval("self.#{method_name}.present?")
  rescue
    return false
  end
end

#restrictedObject



185
186
187
# File 'app/models/goldencobra/article.rb', line 185

def restricted
  Goldencobra::Permission.restricted?(self)
end

#searchable_in_article_typeObject

Gibt ein Textstring zurück der bei den speziellen Artiekltypen für die Volltextsuche durchsucht werden soll



278
279
280
281
282
283
284
285
286
287
# File 'app/models/goldencobra/article.rb', line 278

def searchable_in_article_type
  @searchable_in_article_type_result ||= begin
    related_object = self.get_related_object
    if related_object && related_object.respond_to?(:fulltext_searchable_text)
      related_object.fulltext_searchable_text
    else
      " "
    end
  end
end

#selected_layoutObject



332
333
334
335
336
337
338
339
340
341
342
# File 'app/models/goldencobra/article.rb', line 332

def selected_layout
  if self.template_file.blank?
    if self.articletype.present? && self.articletype.default_template_file.present?
      self.articletype.default_template_file
    else
      "application"
    end
  else
    self.template_file
  end
end

#set_active_sinceObject



661
662
663
# File 'app/models/goldencobra/article.rb', line 661

def set_active_since
  self.active_since = self.created_at
end

#set_index_article_idObject



728
729
730
731
732
733
734
735
736
737
738
# File 'app/models/goldencobra/article.rb', line 728

def set_index_article_id
  return unless self.kind_of_article_type == "Index"
  return if self.article_for_index_id.present?

  # Save without callbacks
  if Rails::VERSION::MAJOR == 3
    self.update_column(:article_for_index_id, self.id)
  elsif Rails::VERSION::MAJOR > 3
    self.update_columns(article_for_index_id: self.id)
  end
end

#set_redirection_step_1Object

bevor ein Artikle gespeichert wird , wird ein redirector unvollständig erstellt



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# File 'app/models/goldencobra/article.rb', line 599

def set_redirection_step_1
  #Wenn der Artikle vor mehr als 24 Stunden erstellt wurde und sich an der URL etwas verändert hat, dann eine Weiterleitung anlegen.
  modified_hours_since = ((Time.now - self.created_at) / 1.hour).round
  if !self.new_record? && (self.url_path_changed? || self.url_name_changed? || self.ancestry_changed?) && modified_hours_since > 24
    #Erstelle Redirector nur mit source
    if self.url_path_changed?
      old_url = "#{self.absolute_base_url}#{Goldencobra::Domain.current.try(:url_prefix)}#{self.url_path_change[0]}"
    else
      old_url = "#{self.absolute_base_url}#{Goldencobra::Domain.current.try(:url_prefix)}#{self.url_path}"
    end
    r = Goldencobra::Redirector.find_by_source_url(old_url)
    if r.blank?
      r = Goldencobra::Redirector.create(source_url: old_url)
    end
    r.active = false
    r.save
    self.create_redirection = r.id
  end
end

#set_redirection_step_2Object



619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'app/models/goldencobra/article.rb', line 619

def set_redirection_step_2
  if self.create_redirection.present? && self.create_redirection.to_i > 0
    #Suche Redirector nur mit source und vervollständige ihn
    Goldencobra::Redirector.where(source_url: self.absolute_public_url).destroy_all
    r = Goldencobra::Redirector.find_by_id(self.create_redirection)
    if r.present?
      r.target_url = self.absolute_public_url
      r.active = true
      r.save
      custom_children = Goldencobra::Article.where(ancestry: "#{self.ancestry}/#{self.id}")
      if custom_children.any?
        if custom_children.count < 30
          # wenn es nur wenige Kinderartikel gibt, dann gleich direkt machen
          custom_children.each do |d|
            d.updated_at = Time.now
            d.url_path = d.get_url_from_path
            d.save
          end
        else
          #Ansosnten einen Raketask damit starten
          system("cd #{::Rails.root} && RAILS_ENV=#{::Rails.env} bundle exec rake article_cache:recreate ID=#{self.id} &")
        end
      end
    end
  end
end

#set_standard_application_templateObject



716
717
718
719
720
721
722
723
724
725
726
# File 'app/models/goldencobra/article.rb', line 716

def set_standard_application_template
  if ActiveRecord::Base.connection.table_exists?("goldencobra_articles") && ActiveRecord::Base.connection.table_exists?("goldencobra_articletypes")
    if self.template_file.blank?
      if self.articletype.present? && self.articletype.default_template_file.present?
        self.template_file = self.articletype.default_template_file
      else
        self.template_file = "application"
      end
    end
  end
end

#set_title_from_breadcrumbObject



585
586
587
588
589
590
591
# File 'app/models/goldencobra/article.rb', line 585

def set_title_from_breadcrumb
  if self.title.blank? && self.breadcrumb.present?
    self.title = self.breadcrumb
  end

  true
end

#set_url_name_if_blankObject



697
698
699
700
701
# File 'app/models/goldencobra/article.rb', line 697

def set_url_name_if_blank
  if self.url_name.blank?
    self.url_name = self.breadcrumb.urlize(downcase: true, convert_spaces: true).gsub("_", "-")
  end
end

#set_url_pathObject



646
647
648
# File 'app/models/goldencobra/article.rb', line 646

def set_url_path
  self.update_column(:url_path, self.get_url_from_path)
end

#uniqify_url_nameString

append counter, if url_name is already used in siblings

news => news–2

Returns:

  • (String)

    url_name



708
709
710
711
712
713
714
# File 'app/models/goldencobra/article.rb', line 708

def uniqify_url_name
  similar_names = self.siblings.pluck(:url_name).select{|c| c.split("--")[0] == self.url_name }
  if similar_names.count > 1
    last_used_number = similar_names.map{|v| v.split("--")[1].to_i}.compact.max
    self.url_name = [self.url_name, last_used_number + 1].join("--")
  end
end

#update_article_urlsboolean

creates and updates external url table

only update URLs if there were any changes on the url

Returns:

  • (boolean)

    Goldencobra::AricleUrl.setup() response



577
578
579
580
581
582
583
# File 'app/models/goldencobra/article.rb', line 577

def update_article_urls
  if previous_changes["startpage"] || previous_changes["url_path"] ||
     previous_changes["url_name"] || previous_changes["ancestry"] ||
     urls.blank?
    Goldencobra::ArticleUrl.setup(id)
  end
end

#update_parent_article_etagObject

Nachdem ein Artikel gelöscht oder aktualsisiert wurde soll sein Elternelement aktualisiert werden, damit ein rss feed oder ähnliches mitbekommt wenn ein kindeintrag gelöscht oder bearbeitet wurde



655
656
657
658
659
# File 'app/models/goldencobra/article.rb', line 655

def update_parent_article_etag
  if self.parent.present?
    self.parent.update_attributes(updated_at: Time.now)
  end
end

#verify_existence_of_opengraph_imageObject



676
677
678
679
680
681
682
683
684
685
686
687
# File 'app/models/goldencobra/article.rb', line 676

def verify_existence_of_opengraph_image
  if self.metatag_open_graph_image.blank?
    if self.article_images.any? && self.article_images.first.present? &&
       self.article_images.first.image.present? &&
       self.article_images.first.image.image.present?
      og_img_val = "#{self.absolute_base_url}#{self.article_images.first.image.image.url}"
    else
      og_img_val = Goldencobra::Setting.for_key("goldencobra.facebook.opengraph_default_image")
    end
    self.metatag_open_graph_image = og_img_val
  end
end