Module: LogTable::ClassMethods
- Defined in:
- lib/log_table.rb
Constant Summary collapse
- INSERTED =
'inserted'- UPDATED =
'updated'- DELETED =
'deleted'
Instance Method Summary collapse
-
#add_log_trigger(options = {}) ⇒ Object
add_log_trigger will add hairtrigger triggers to the model.
- #sql_func(status, options) ⇒ Object
Instance Method Details
#add_log_trigger(options = {}) ⇒ Object
add_log_trigger will add hairtrigger triggers to the model. It will generate triggers for :insert and :update.
Options:
-
:table_name - Specify table name of the log table.
56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/log_table.rb', line 56 def add_log_trigger( = {}) trigger.after(:insert) do sql_func(INSERTED, ) end trigger.after(:update) do sql_func(UPDATED, ) end trigger.after(:delete) do sql_func(DELETED, ) end end |
#sql_func(status, options) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/log_table.rb', line 24 def sql_func(status, ) col_names = column_names # Avoid any unnecessary round trips to the database db_columns = [STATUS_COLUMN_NAME] + col_names.map { |col_name| col_name == 'id' ? "#{model_name.to_s.underscore}_id" : "#{col_name}" } db_columns_str = db_columns.join(', ') values = ["\"#{status}\""] col_prefix = status == DELETED ? 'OLD' : 'NEW' values += col_names.map { |col| "#{col_prefix}.#{col}" } values_str = values.join(', ') log_table_name = [:table_name] || "#{table_name}_log" sql = "INSERT INTO #{log_table_name}(#{db_columns_str}) VALUES (#{values_str})" sql end |