-
Notifications
You must be signed in to change notification settings - Fork 336
[How to] Create custom activities
Besides standard, automatic activities created on CRUD actions on your model (deactivatable), you can post your own activities that can be triggered without modifying the tracked model. There are a few ways to do this, as PublicActivity gives three tiers of options to be set.
Because every activity needs a key (otherwise: NoKeyProvided
is raised), the shortest and minimal way to post an activity is:
@user.create_activity :mood_changed
# the key of the action will be user.mood_changed
@user.create_activity action: :mood_changed # this is exactly the same as above
Besides assigning your key (which is obvious from the code), it will take global options from User class (given in #tracked
method during class definition) and overwrite them with instance options (set on @user
by #activity
method). You can read more about options and how PublicActivity inherits them for you here.
Note the action parameter builds the key like this: "#{model_name}.#{action}"
. You can read further on options for #create_activity
here.
To provide more options, you can do:
@user.create_activity action: 'poke', params: {reason: 'bored'}, recipient: @friend, owner: @user
In this example, we have provided all the things we could for a standard Activity.
It is sometimes unavoidable to assign options in a more sophisticated way, where oneliners are not possible. For this case, we provide instance options, which are reset every time activity is created.
@user.activity key: 'user.mood_changed' # sets instance options
@user.create_activity # ok, key is set, passes validation => activity is saved
# here instance options are not set again
@user.create_activity # ERROR: NoKeyProvided