Sha256: cab54e13cb01ec336ea31f751612a23931a30fd436bc90ee9a82e565b80e2723

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 KB

Contents

module Feeder
  class FeedableObserver < ::ActiveRecord::Observer
    observe Feeder.config.observables.keys

    def after_create(feedable)
      options = options_for feedable

      if condition = options[:if]
        if condition.respond_to? :call
          return unless condition.call feedable
        else
          return unless feedable.send condition
        end
      end

      feedable.create_feeder_item! do |item|
        item.feedable     = feedable
        item.created_at   = feedable.created_at
        item.published_at = Time.zone.now

        if feedable.respond_to? :sticky
          item.sticky = feedable.sticky
        end
      end
    end

    def after_save(feedable)
      item = feedable.feeder_item

      if item
        if feedable.respond_to? :sticky
          item.sticky = feedable.sticky
        end

        item.save!
      end
    end

    private

    def options_for(feedable)
      (observables[feedable.class] || observables[feedable.class.to_s]) or raise StandardError, "#{feedable} is not observed"
    end

    def observables
      Feeder.config.observables
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
feeder-0.5.1 app/models/feeder/feedable_observer.rb