Skip to content

Instantly share code, notes, and snippets.

@Zhomart
Last active October 22, 2016 06:14
Show Gist options
  • Save Zhomart/07f32bd1635711471b94baaca9a6df34 to your computer and use it in GitHub Desktop.
Save Zhomart/07f32bd1635711471b94baaca9a6df34 to your computer and use it in GitHub Desktop.
# app/models/concerns/history_field_concern.rb
module HistoryFieldConcern
extend ActiveSupport::Concern
# consider using "before_save" and Changable
# https://github.com/mongodb/mongoid/blob/master/lib/mongoid/changeable.rb
included do
end
class_methods do
# @param name [Symbol]
# @param opts [Hash]
def history_field(name, opts)
field name, opts
field "#{name}_history", type: Array, default: -> { Array.new }
end
# @param name [Symbol]
def history_belongs_to(model)
belongs_to model # it creates field :"model_id"
field "#{model}_id_history", type: Array, default: -> { Array.new }
end
end
end
class Reservation
include Mongoid::Document
include Mongoid::Timestamps
include HistoryFieldConcern
field :synced_at, type: Time # sync time with client
field :removed, type: Boolean, default: false
history_field :name, type: String, default: nil
belongs_to :salon
history_belongs_to :master
end
class Master
include Mongoid::Document
include Mongoid::Timestamps
include HistoryFieldConcern
history_field :first_name, type: String
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment