Module: Fera::HasTimestampAction::ClassMethods

Defined in:
lib/fera/models/concerns/has_timestamp_action.rb

Instance Method Summary collapse

Instance Method Details

#timestamp_action(args) ⇒ Object

define API actions that set a timestamp on the model

Examples:

class Order < Fera::Base
  include HasTimestampAction

  timestamp_action deliver: :delivered
end

routes to `PUT /orders/1/deliver`

order = Order.find(1)
order.delivered? # => false
order.deliver!(Time.now)
order.delivered? # => true
order.delivered_at # => 2018-01-01 00:00:00 UTC

or

Fera::Order.deliver!(1, Time.now.utc)

Parameters:

  • actions (Array<Symbol>)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/fera/models/concerns/has_timestamp_action.rb', line 29

def timestamp_action(args)
  args.each do |action, state|
    define_method("#{ action }!") do |at = nil|
      changed_attributes = { "#{ state }_at": at.presence || Time.now.utc }

      put(action, changed_attributes)

      load(changed_attributes)

      true
    end

    define_method("#{ state }?") do
      send("#{ state }_at?")
    end

    define_singleton_method("#{ action }!") do |id, at = nil|
      find(id).send("#{ action }!", at)
    end
  end
end