Project

beaconable

0.0
Low commit activity in last 3 years
A long-lived project that still receives updates
Small OO patern to isolate side-effects and callbacks for your ActiveRecord Models
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Development

~> 1.16
~> 10.0
~> 5.0
~> 13.0
~> 0.74.0
~> 1.3

Runtime

 Project Readme

Beaconable

Gem Version CI contributions welcome

A lightweight Ruby gem that provides an elegant, object-oriented pattern for isolating side-effects and callbacks from your ActiveRecord models.

Why Beaconable?

ActiveRecord callbacks (after_save, after_commit, etc.) are convenient, but they can quickly turn your models into tangled messes of business logic, external API calls, and notification triggers. Before you know it, your User model is sending emails, syncing with Salesforce, updating Elasticsearch, and making your tests take forever.

Beaconable solves this by:

  • Separating concerns — Side-effects live in dedicated Beacon classes, not your models
  • Improving testability — Test your model logic and side-effects independently
  • Providing context — Your Beacon knows exactly what changed (object_was vs object)
  • Keeping models lean — Your ActiveRecord models stay focused on data and validations
  • Offering flexibility — Skip beacons when needed, pass metadata for conditional logic

Requirements

  • Ruby >= 3.2.0
  • Rails >= 7.0

Installation

Add this line to your application's Gemfile:

gem 'beaconable'

And then execute:

$ bundle

Or install it yourself as:

$ gem install beaconable

Usage

When you include Beaconable in your model it will fire your Beacon everytime after you create or save an entry. Inside your Beacon you have access to the following:

  • object (and an alias with the name of your model, i.e user): the instance of your object after changes.
  • object_was (and an alias with the name of your model, i.e. user_was): the instance of your object as it was before your changes
  • field_changed?(:field_name) : It allows you to check if a specific field was modified.
  • any_field_changed?(:field_name, :other_field_name) : It allows you to check if any of multiple fields was modified.
  • new_entry? : Returns true if the item saved is new
  • destroyed_entry? : Returns true if the item has been destroyed

You can also used the following chained methods

  • field_change(:field_name).from('first_alternative', 'n_alternative').to('first_alternative_for_to', 'second_alternative_for_to', 'n_alternative_for_toq')

Rails Generator

You can use the bundled generator if you are using the library inside of a Rails project:

rails g beacon User

This will do the following:

  1. Create a new beacon file in app/beacons/user_beacon.rb
  2. Will add "include Beaconable" in your User Model.

Beacon Definition

class UserBeacon < Beaconable::BaseBeacon
  alias user object
  alias user_was object_was

  def call
    WelcomeUserJob.perform_later(self.id) if new_entry?
    UpdateExternalServiceJob.perform_later(self.id) if field_changed? :email
  end
end

Avoid firing a beacon

You can skip beacon calls if you pass true to the method #skip_beacon. I.E:

...
 user.update(user_params)
 user.skip_beacon = true
 user.save # The user beacon won't be fired.

Beacon metadata

You can pass beacon_metadata to the object that will be available on the Beacon.

Some uses might be:

  • to determine whether a certain action should be performed or not. For example when creating users in batch actions or in through the console you might want to skip just the welcome email but still perform all the other side effects associated with the user creation.
  • to pass information that is generated / available in memory, will not be persisted in the model but is relevant in the side effects. For example, if you want to implement your own event logging system you could pass the current user id from the controller action to the beacon where you are going to create the Event.
User.create(
  email: "new_user@email.com",
  beacon_metadata: {
    skip_welcome_user_job: true,
    triggered_by: "admin@myapp.com"
  }
)

# app/beacons/user_beacon.rb
class UserBeacon < Beaconable::BaseBeacon
  alias user object
  alias user_was object_was

  def call
    WelcomeUserJob.perform_later(self.id) if should_perform_welcome_user_job?
    UpdateExternalServiceJob.perform_later(self.id) if field_changed? :email
    Event.create do |event|
      event.content = UserSerializer.new(user).event_content
      event.ocurred_at = user.updated_at
      if beacon_metadata.present?
        event.triggered_by = beacon_metadata.dig(:triggered_by)
        event.source = beacon_metadata.dig(:source)
      end
    end
  end

  private

  def should_perform_welcome_user_job?
    new_entry? && !skip_welcome_user_job?
  end

  def skip_welcome_user_job?
    beacon_metadata[:skip_welcome_user_job] if beacon_metadata.present?
  end
end

Important: once the beacon has been fired the beacon_metadata will be cleared.

Multiple saves in a transaction (a.k.a. "Please don't do this")

Fair warning: If you're doing multiple saves on the same record within a single transaction, you might want to reconsider your life choices. But hey, we don't judge — we just handle it gracefully.

Beaconable captures the state of your object at the first before_save and holds onto it until after_commit. This means that if you do something like this:

ActiveRecord::Base.transaction do
  user.update!(status: 'pending')
  user.update!(status: 'verified')
  user.update!(status: 'active')
end

Your beacon will see:

  • object.status'active' (the final value)
  • object_was.status → whatever it was before the transaction started

This is intentional! We track the change from the original state to the final committed state, not the intermediate chaos in between.

# In your beacon:
def call
  if field_changed?(:status)
    # This will be true if status changed from its original value
    # to the final committed value — regardless of how many
    # intermediate updates happened
    NotifyStatusChange.perform_later(user.id)
  end
end

Why? Because Rails' native saved_changes only shows the last save, which would miss the fact that status changed at all if only the first update modified it. We've got your back.

Known Limitations

Encrypted columns with non-deterministic encryption

If you're using Rails encrypted attributes with a non-deterministic algorithm, field_changed? will return true even when the plaintext value hasn't changed. This happens because the ciphertext changes on every save:

bank_account.routing_number = bank_account.routing_number  # Same value!
bank_account.changes_to_save
# => {"routing_number_ciphertext" => ["QnPUYDD...", "IDZIchs..."]}

The underlying ciphertext is different, so Rails (and Beaconable) sees it as a change. If this is a problem for your use case, consider using deterministic encryption for those columns, or handle the comparison manually in your beacon.

Store accessor attributes

Attributes defined via store_accessor are not directly supported by field_changed?. Rails tracks changes on the underlying store column, not on individual accessor keys:

# Given: store_accessor :data_store, :a_store_attribute

user.a_store_attribute = "hello"
user.changes_to_save
# => {"data_store" => [{}, {"a_store_attribute" => "hello"}]}

# In your beacon:
field_changed?(:a_store_attribute)  # => false (won't work)
field_changed?(:data_store)         # => true (works, but less precise)

Workaround: Check the underlying store column and inspect its contents:

def call
  if field_changed?(:data_store)
    old_store = object_was[:data_store] || {}
    new_store = object.data_store || {}

    if old_store["a_store_attribute"] != new_store["a_store_attribute"]
      # Handle the change
    end
  end
end

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/Lastimoso/beaconable. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Beaconable project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.