Skip to content

Bad examples in README #2

@Mange

Description

@Mange

So this was extracted from Rails since most people used observers wrong. Don't you think that examples that uses them in a bad way might invite people to make those mistakes again and again?

Observers should work with persistence, with concerns that shouldn't really be directly in the model. Here's some examples:

class PostObserver < ActiveRecord::Observer
  def after_destroy(post)
    destroy_unused_tags(post.tags)
  end

  private
  def destroy_unused_tags(changed_tags)
    changed_tags.each do |tag|
      tag.destroy if tag.taggings.empty?
    end
  end
end
class PageViewingObserver < ActiveModel::Observer
  def after_create(page_viewing)
    # Assuming the following models work by caching counters and then incrementing them (speed by denormalization, MongoDB, etc.)
    VisitorStatistics.increase_monthly_stats(page_viewing.visitor)
    PageStatistics.increase_monthly_stats(page_viewing.page)
  end
end

Sure, these might still not be optimal, but they are better than an example that sends an email from the persistence layer, every time a model is persisted. Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions