├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── MIT-LICENSE ├── README.md ├── Rakefile ├── app ├── assets │ ├── javascripts │ │ └── rails_admin │ │ │ ├── diff_match_patch.js │ │ │ ├── jquery.pretty-text-diff.js │ │ │ └── ra.history.js │ └── stylesheets │ │ └── rails_admin │ │ └── ra.history.css └── views │ ├── .keep │ └── rails_admin │ └── main │ ├── _dashboard_history.html.haml │ ├── _version.html.haml │ └── history.html.haml ├── bin └── rails ├── config └── locales │ ├── history_rollback.en.yml │ ├── history_rollback.ru.yml │ ├── history_rollback.zh_cn.yml │ └── pt-BR.yml ├── lib ├── rails_admin_history_rollback.rb └── rails_admin_history_rollback │ ├── config │ └── actions │ │ └── history_index.rb │ ├── engine.rb │ ├── extensions │ └── paper_trail │ │ └── auditing_adapter.rb │ └── version.rb ├── rails_admin_history_rollback.gemspec └── screenshots ├── history.png └── modal.png /.gitignore: -------------------------------------------------------------------------------- 1 | .bundle/ 2 | log/*.log 3 | pkg/ 4 | 5 | *.gem 6 | *.rbc 7 | .config 8 | .yardoc 9 | Gemfile.lock 10 | InstalledFiles 11 | _yardoc 12 | coverage 13 | doc/ 14 | lib/bundler/man 15 | rdoc 16 | spec/reports 17 | test/tmp 18 | test/version_tmp 19 | tmp 20 | .DS_Store 21 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hello@jemco.de. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | Submitting a Pull Request: 3 | 4 | 1. [Fork the repository.][fork] 5 | 2. [Create a topic branch.][branch] 6 | 3. Implement your feature or bug fix. 7 | 4. Add, commit, and push your changes. 8 | 5. [Submit a pull request.][pr] 9 | 10 | [fork]: http://help.github.com/fork-a-repo/ 11 | [branch]: http://learn.github.com/p/branching.html 12 | [pr]: http://help.github.com/send-pull-requests/ 13 | -------------------------------------------------------------------------------- /MIT-LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2015 Rikki Pitt 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rails Admin History Rollback 2 | 3 | [![Gem Version](https://badge.fury.io/rb/rails_admin_history_rollback.svg)](http://badge.fury.io/rb/rails_admin_history_rollback) 4 | [![Code Climate](https://codeclimate.com/github/rikkipitt/rails_admin_history_rollback/badges/gpa.svg)](https://codeclimate.com/github/rikkipitt/rails_admin_history_rollback) 5 | 6 | [RailsAdmin](https://github.com/sferik/rails_admin) extension for enabling users to easily visualise and revert their history audit created by the [PaperTrail](https://github.com/airblade/paper_trail) gem. 7 | 8 | ## Installation 9 | 10 | To enable **rails_admin_history_rollback**, add the following to your `Gemfile` ensuring it is added *after* rails_admin: 11 | 12 | ```ruby 13 | gem 'rails_admin' 14 | gem 'rails_admin_history_rollback' 15 | ``` 16 | 17 | It should go without saying that this plugin also requires the paper_trail gem. 18 | 19 | E.g. `gem 'paper_trail'` 20 | 21 | 22 | ## Configuration 23 | Simply enable paper_trail on your model `--with-changes --with-associations` and set up as usual by following the [paper_trail](https://github.com/airblade/paper_trail) instructions. 24 | 25 | ```bash 26 | rails generate paper_trail:install --with-changes --with-associations 27 | ``` 28 | 29 | In the `rails_admin.rb` initializer, uncomment the following lines to enable auditing: 30 | 31 | ```ruby 32 | history_index 33 | history_show 34 | ``` 35 | 36 | ## Notes 37 | 38 | You may also need to `require "paper_trail"` in `application.rb` 39 | 40 | As pointed out in issue [#8](https://github.com/rikkipitt/rails_admin_history_rollback/issues/8), `paper_trail` master branch and release [v5.0.0](https://github.com/airblade/paper_trail/blob/master/CHANGELOG.md#500-unreleased) (when available) causes session issues. Login is reset by devise; `paper_trail` tries to access to the `current_user` variable before `devise` ([airblade/paper_trail#556](https://github.com/airblade/paper_trail#556)). 41 | 42 | The fix is to manually add `set_paper_trail_whodunnit` before_action as advised here: (https://github.com/airblade/paper_trail#finding-out-who-was-responsible-for-a-change) 43 | 44 | ```ruby 45 | # app/controllers/application_controller.rb 46 | class ApplicationController < ActionController::Base 47 | [...] 48 | before_action :set_paper_trail_whodunnit 49 | [...] 50 | end 51 | ``` 52 | 53 | ## Screenshots 54 | 55 | ![History view](https://github.com/rikkipitt/rails_admin_history_rollback/raw/main/screenshots/history.png "history view") 56 | 57 | ![Modal view](https://github.com/rikkipitt/rails_admin_history_rollback/raw/main/screenshots/modal.png "modal view") 58 | 59 | ## About Jemcode 60 | 61 | [Jemcode][hire] 62 | 63 | This repository is maintained and funded by Jemcode Limited. We are [available for hire][hire]. 64 | 65 | [hire]: https://www.jemco.de?utm_source=github 66 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env rake 2 | require "bundler/gem_tasks" 3 | -------------------------------------------------------------------------------- /app/assets/javascripts/rails_admin/diff_match_patch.js: -------------------------------------------------------------------------------- 1 | (function(){function diff_match_patch(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=0.5;this.Match_Distance=1E3;this.Patch_DeleteThreshold=0.5;this.Patch_Margin=4;this.Match_MaxBits=32} 2 | diff_match_patch.prototype.diff_main=function(a,b,c,d){"undefined"==typeof d&&(d=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1E3*this.Diff_Timeout);if(null==a||null==b)throw Error("Null input. (diff_main)");if(a==b)return a?[[0,a]]:[];"undefined"==typeof c&&(c=!0);var e=c,f=this.diff_commonPrefix(a,b);c=a.substring(0,f);a=a.substring(f);b=b.substring(f);var f=this.diff_commonSuffix(a,b),g=a.substring(a.length-f);a=a.substring(0,a.length-f);b=b.substring(0,b.length-f);a=this.diff_compute_(a, 3 | b,e,d);c&&a.unshift([0,c]);g&&a.push([0,g]);this.diff_cleanupMerge(a);return a}; 4 | diff_match_patch.prototype.diff_compute_=function(a,b,c,d){if(!a)return[[1,b]];if(!b)return[[-1,a]];var e=a.length>b.length?a:b,f=a.length>b.length?b:a,g=e.indexOf(f);return-1!=g?(c=[[1,e.substring(0,g)],[0,f],[1,e.substring(g+f.length)]],a.length>b.length&&(c[0][0]=c[2][0]=-1),c):1==f.length?[[-1,a],[1,b]]:(e=this.diff_halfMatch_(a,b))?(f=e[0],a=e[1],g=e[2],b=e[3],e=e[4],f=this.diff_main(f,g,c,d),c=this.diff_main(a,b,c,d),f.concat([[0,e]],c)):c&&100c);v++){for(var n=-v+r;n<=v-t;n+=2){var l=g+n,m;m=n==-v||n!=v&&j[l-1]d)t+=2;else if(s>e)r+=2;else if(q&&(l=g+k-n,0<=l&&l= 8 | u)return this.diff_bisectSplit_(a,b,m,s,c)}}for(n=-v+p;n<=v-w;n+=2){l=g+n;u=n==-v||n!=v&&i[l-1]d)w+=2;else if(m>e)p+=2;else if(!q&&(l=g+k-n,0<=l&&(l=u)))return this.diff_bisectSplit_(a,b,m,s,c)}}return[[-1,a],[1,b]]}; 9 | diff_match_patch.prototype.diff_bisectSplit_=function(a,b,c,d,e){var f=a.substring(0,c),g=b.substring(0,d);a=a.substring(c);b=b.substring(d);f=this.diff_main(f,g,!1,e);e=this.diff_main(a,b,!1,e);return f.concat(e)}; 10 | diff_match_patch.prototype.diff_linesToChars_=function(a,b){function c(a){for(var b="",c=0,f=-1,g=d.length;fd?a=a.substring(c-d):c=a.length?[h,j,n,l,g]:null}if(0>=this.Diff_Timeout)return null; 15 | var d=a.length>b.length?a:b,e=a.length>b.length?b:a;if(4>d.length||2*e.lengthd[4].length?g:d:d:g;var j;a.length>b.length?(g=h[0],d=h[1],e=h[2],j=h[3]):(e=h[0],j=h[1],g=h[2],d=h[3]);h=h[4];return[g,d,e,j,h]}; 16 | diff_match_patch.prototype.diff_cleanupSemantic=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=0,h=0,j=0,i=0;f=e){if(d>=b.length/2||d>=c.length/2)a.splice(f,0,[0,c.substring(0,d)]),a[f-1][1]=b.substring(0,b.length-d),a[f+1][1]=c.substring(d),f++}else if(e>=b.length/2||e>=c.length/2)a.splice(f,0,[0,b.substring(0,e)]),a[f-1][0]=1,a[f-1][1]=c.substring(0,c.length-e),a[f+1][0]=-1,a[f+1][1]=b.substring(e),f++;f++}f++}}; 18 | diff_match_patch.prototype.diff_cleanupSemanticLossless=function(a){function b(a,b){if(!a||!b)return 6;var c=a.charAt(a.length-1),d=b.charAt(0),e=c.match(diff_match_patch.nonAlphaNumericRegex_),f=d.match(diff_match_patch.nonAlphaNumericRegex_),g=e&&c.match(diff_match_patch.whitespaceRegex_),h=f&&d.match(diff_match_patch.whitespaceRegex_),c=g&&c.match(diff_match_patch.linebreakRegex_),d=h&&d.match(diff_match_patch.linebreakRegex_),i=c&&a.match(diff_match_patch.blanklineEndRegex_),j=d&&b.match(diff_match_patch.blanklineStartRegex_); 19 | return i||j?5:c||d?4:e&&!g&&h?3:g||h?2:e||f?1:0}for(var c=1;c=i&&(i=k,g=d,h=e,j=f)}a[c-1][1]!=g&&(g?a[c-1][1]=g:(a.splice(c-1,1),c--),a[c][1]= 20 | h,j?a[c+1][1]=j:(a.splice(c+1,1),c--))}c++}};diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch.whitespaceRegex_=/\s/;diff_match_patch.linebreakRegex_=/[\r\n]/;diff_match_patch.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/; 21 | diff_match_patch.prototype.diff_cleanupEfficiency=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=!1,h=!1,j=!1,i=!1;fb)break;e=c;f=d}return a.length!=g&&-1===a[g][0]?f:f+(b-e)}; 25 | diff_match_patch.prototype.diff_prettyHtml=function(a){for(var b=[],c=/&/g,d=//g,f=/\n/g,g=0;g");switch(h){case 1:b[g]=''+j+"";break;case -1:b[g]=''+j+"";break;case 0:b[g]=""+j+""}}return b.join("")}; 26 | diff_match_patch.prototype.diff_text1=function(a){for(var b=[],c=0;cthis.Match_MaxBits)throw Error("Pattern too long for this browser.");var e=this.match_alphabet_(b),f=this,g=this.Match_Threshold,h=a.indexOf(b,c);-1!=h&&(g=Math.min(d(0,h),g),h=a.lastIndexOf(b,c+b.length),-1!=h&&(g=Math.min(d(0,h),g)));for(var j=1<=i;p--){var w=e[a.charAt(p-1)];k[p]=0===t?(k[p+1]<<1|1)&w:(k[p+1]<<1|1)&w|((r[p+1]|r[p])<<1|1)|r[p+1];if(k[p]&j&&(w=d(t,p-1),w<=g))if(g=w,h=p-1,h>c)i=Math.max(1,2*c-h);else break}if(d(t+1,c)>g)break;r=k}return h}; 32 | diff_match_patch.prototype.match_alphabet_=function(a){for(var b={},c=0;c=2*this.Patch_Margin&& 37 | e&&(this.patch_addContext_(a,h),c.push(a),a=new diff_match_patch.patch_obj,e=0,h=d,f=g)}1!==i&&(f+=k.length);-1!==i&&(g+=k.length)}e&&(this.patch_addContext_(a,h),c.push(a));return c};diff_match_patch.prototype.patch_deepCopy=function(a){for(var b=[],c=0;cthis.Match_MaxBits){if(j=this.match_main(b,h.substring(0,this.Match_MaxBits),g),-1!=j&&(i=this.match_main(b,h.substring(h.length-this.Match_MaxBits),g+h.length-this.Match_MaxBits),-1==i||j>=i))j=-1}else j=this.match_main(b,h,g); 39 | if(-1==j)e[f]=!1,d-=a[f].length2-a[f].length1;else if(e[f]=!0,d=j-g,g=-1==i?b.substring(j,j+h.length):b.substring(j,i+this.Match_MaxBits),h==g)b=b.substring(0,j)+this.diff_text2(a[f].diffs)+b.substring(j+h.length);else if(g=this.diff_main(h,g,!1),h.length>this.Match_MaxBits&&this.diff_levenshtein(g)/h.length>this.Patch_DeleteThreshold)e[f]=!1;else{this.diff_cleanupSemanticLossless(g);for(var h=0,k,i=0;ie[0][1].length){var f=b-e[0][1].length;e[0][1]=c.substring(e[0][1].length)+e[0][1];d.start1-=f;d.start2-=f;d.length1+=f;d.length2+=f}d=a[a.length-1];e=d.diffs;0==e.length||0!=e[e.length-1][0]?(e.push([0, 42 | c]),d.length1+=b,d.length2+=b):b>e[e.length-1][1].length&&(f=b-e[e.length-1][1].length,e[e.length-1][1]+=c.substring(0,f),d.length1+=f,d.length2+=f);return c}; 43 | diff_match_patch.prototype.patch_splitMax=function(a){for(var b=this.Match_MaxBits,c=0;c2*b?(h.length1+=i.length,e+=i.length,j=!1,h.diffs.push([g,i]),d.diffs.shift()):(i=i.substring(0,b-h.length1-this.Patch_Margin),h.length1+=i.length,e+=i.length,0===g?(h.length2+=i.length,f+=i.length):j=!1,h.diffs.push([g,i]),i==d.diffs[0][1]?d.diffs.shift():d.diffs[0][1]=d.diffs[0][1].substring(i.length))}g=this.diff_text2(h.diffs);g=g.substring(g.length-this.Patch_Margin);i=this.diff_text1(d.diffs).substring(0,this.Patch_Margin);""!==i&& 45 | (h.length1+=i.length,h.length2+=i.length,0!==h.diffs.length&&0===h.diffs[h.diffs.length-1][0]?h.diffs[h.diffs.length-1][1]+=i:h.diffs.push([0,i]));j||a.splice(++c,0,h)}}};diff_match_patch.prototype.patch_toText=function(a){for(var b=[],c=0;c/g; 58 | pattern_para = /\n/g; 59 | operation = diff[0], data = diff[1]; 60 | text = data.replace(pattern_amp, '&').replace(pattern_lt, '<').replace(pattern_gt, '>').replace(pattern_para, '
'); 61 | switch (operation) { 62 | case DIFF_INSERT: 63 | return '' + text + ''; 64 | case DIFF_DELETE: 65 | return '' + text + ''; 66 | case DIFF_EQUAL: 67 | return '' + text + ''; 68 | } 69 | }; 70 | 71 | }).call(this); 72 | -------------------------------------------------------------------------------- /app/assets/javascripts/rails_admin/ra.history.js: -------------------------------------------------------------------------------- 1 | (function($) { 2 | $.widget("ra.history", { 3 | 4 | _create: function() { 5 | var widget = this; 6 | var dom_widget = widget.element; 7 | 8 | var changesetLink = dom_widget.find('a.changeset'); 9 | changesetLink.unbind().bind("click", function(e){ 10 | widget._bindModalOpening(e, $(this).data('url')); 11 | return false; 12 | }); 13 | }, 14 | 15 | _bindModalOpening: function(e, url) { 16 | e.preventDefault(); 17 | widget = this; 18 | if($("#modal").length) 19 | return false; 20 | 21 | var dialog = this._getModal(); 22 | 23 | setTimeout(function(){ // fix race condition with modal insertion in the dom (Chrome => Team/add a new fan => #modal not found when it should have). Somehow .on('show') is too early, tried it too. 24 | $.ajax({ 25 | url: url, 26 | beforeSend: function(xhr) { 27 | xhr.setRequestHeader("Accept", "text/javascript"); 28 | }, 29 | success: function(data, status, xhr) { 30 | dialog.find('.modal-body').html(data); 31 | widget._bindFormEvents(); 32 | }, 33 | error: function(xhr, status, error) { 34 | dialog.find('.modal-body').html(xhr.responseText); 35 | }, 36 | dataType: 'text' 37 | }); 38 | },100); 39 | 40 | }, 41 | 42 | _bindFormEvents: function() { 43 | var widget = this, 44 | dialog = this._getModal(), 45 | table = dialog.find("table") 46 | saveButton = dialog.find('.save-action'); 47 | 48 | dialog.find('.modal-header-title').html(table.data('title')); 49 | dialog.find('.cancel-action').unbind().click(function(){ 50 | dialog.modal('hide'); 51 | return false; 52 | }).html(table.data('cancel')); 53 | 54 | dialog.find('#version tr').prettyTextDiff(); 55 | saveButton.attr('href', table.data('rollbackurl')).data('confirm', table.data('confirm')).html(table.data('rollback')); 56 | }, 57 | 58 | _getModal: function() { 59 | var widget = this; 60 | if (!widget.dialog) { 61 | widget.dialog = $('') 78 | .modal({ 79 | keyboard: true, 80 | backdrop: true, 81 | show: true 82 | }) 83 | .on('hidden.bs.modal', function(){ 84 | widget.dialog.remove(); // We don't want to reuse closed modals 85 | widget.dialog = null; 86 | }); 87 | } 88 | return this.dialog; 89 | } 90 | }); 91 | })(jQuery); 92 | 93 | $(document).on('rails_admin.dom_ready', function() { 94 | $('#history').history(); 95 | }); 96 | -------------------------------------------------------------------------------- /app/assets/stylesheets/rails_admin/ra.history.css: -------------------------------------------------------------------------------- 1 | td.diff { 2 | white-space: normal !important; 3 | } 4 | 5 | ins { 6 | background-color: #c6ffc6; 7 | text-decoration: none; 8 | } 9 | 10 | del { 11 | background-color: #ffc6c6; 12 | } 13 | -------------------------------------------------------------------------------- /app/views/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jemcode/rails_admin_history_rollback/c39e336e0aba75a4059dbf695b9d3d89628b7144/app/views/.keep -------------------------------------------------------------------------------- /app/views/rails_admin/main/_dashboard_history.html.haml: -------------------------------------------------------------------------------- 1 | = stylesheet_link_tag 'rails_admin/ra.history' 2 | = javascript_include_tag 'rails_admin/diff_match_patch' 3 | = javascript_include_tag 'rails_admin/jquery.pretty-text-diff' 4 | = javascript_include_tag 'rails_admin/ra.history' 5 | 6 | %table#history.table.table-condensed.table-striped 7 | %thead 8 | %tr 9 | %th.shrink.user= t("admin.table_headers.username") 10 | %th.shrink.items= t("admin.table_headers.item") 11 | %th.changes= t("admin.history_rollback.table_headers.changes") 12 | %th.rollback= t("admin.history_rollback.table_headers.rollback") 13 | %tbody 14 | - @history.each do |t| 15 | - abstract_model = RailsAdmin.config(t.table).abstract_model 16 | %tr 17 | %td= t.try :username 18 | - if o = abstract_model.try(:get, t.item) 19 | - label = o.send(abstract_model.config.object_label_method) 20 | - if show_action = action(:show, abstract_model, o) 21 | %td= link_to(label, url_for(action: show_action.action_name, model_name: abstract_model.to_param, id: o.id), class: 'pjax') 22 | - else 23 | %td= label 24 | - else 25 | - label = Object.const_defined?(t.table) ? t.table.constantize.model_name.human : t.table 26 | %td= "#{label} ##{t.item}" 27 | %td= t.message 28 | %td 29 | -if history_action = action(:history_index, abstract_model) 30 | = link_to(t("admin.history_rollback.table_headers.view_changes"), "#", class: "changeset", :data => {:url => url_for(action: history_action.action_name, model_name: abstract_model.to_param, version_id: t.version_id)}) 31 | -------------------------------------------------------------------------------- /app/views/rails_admin/main/_version.html.haml: -------------------------------------------------------------------------------- 1 | %table#version.table.table-striped{:data => { :title => "#{@abstract_model} version ##{@version.index + 1} [#{@version.event}]", :rollbackurl => url_for(action: action(:history_index, @abstract_model).action_name, model_name: @abstract_model.to_param, version_id: @version.id), rollback: t("admin.history_rollback.table_headers.rollback"), cancel: t("admin.history_rollback.cancel"), confirm: t("admin.history_rollback.confirm")}} 2 | %thead 3 | %tr 4 | %th= "#{t('admin.history_rollback.table_headers.field')}" 5 | %th{:colspan => 3}= "#{t('admin.history_rollback.table_headers.changes')}" 6 | %tbody 7 | - @version.changeset.sort.each do |changes| 8 | %tr 9 | %td= changes[0] 10 | %td.original.hide= changes[1][0] 11 | %td.changed.hide= changes[1][1] 12 | %td.diff 13 | -------------------------------------------------------------------------------- /app/views/rails_admin/main/history.html.haml: -------------------------------------------------------------------------------- 1 | = stylesheet_link_tag 'rails_admin/ra.history' 2 | = javascript_include_tag 'rails_admin/diff_match_patch' 3 | = javascript_include_tag 'rails_admin/jquery.pretty-text-diff' 4 | = javascript_include_tag 'rails_admin/ra.history' 5 | 6 | - params = request.params.except(:action, :controller, :model_name) 7 | - query = params[:query] 8 | - filter = params[:filter] 9 | - sort = params[:sort] 10 | - sort_reverse = params[:sort_reverse] 11 | - path_method = params[:id] ? "history_show_path" : "history_index_path" 12 | 13 | = form_tag("", method: "get", class: "search pjax-form form-inline") do 14 | .well 15 | .input-group 16 | %input.form-control.input-small{name: "query", type: "search", value: query, placeholder: "#{t("admin.misc.filter")}", class: 'input-small'} 17 | %span.input-group-btn 18 | %button.btn.btn-primary{type: 'submit', :'data-disable-with' => ' '.html_safe + t('admin.misc.refresh')} 19 | %i.icon-white.icon-refresh 20 | = t("admin.misc.refresh") 21 | %table#history.table.table-striped.table-condensed 22 | %thead 23 | %tr 24 | - columns = [] 25 | - columns << { property_name: "created_at", css_class: "created_at",link_text: t('admin.table_headers.created_at') } 26 | - columns << { property_name: "username", css_class: "username", link_text: t('admin.table_headers.username') } 27 | - columns << { property_name: "item", css_class: "item", link_text: t('admin.table_headers.item') } if @general 28 | - columns << { property_name: "message", css_class: "message", link_text: t('admin.table_headers.message') } 29 | - columns << { property_name: "rollback", css_class: "rollback", link_text: t('admin.history_rollback.table_headers.rollback') } 30 | 31 | - columns.each do |column| 32 | - property_name = column[:property_name] 33 | - selected = (sort == property_name) 34 | - sort_direction = (sort_reverse ? "headerSortUp" : "headerSortDown" if selected) 35 | - sort_location = send(path_method, params.except("sort_reverse").merge(model_name: @abstract_model.to_param, sort: property_name).merge(selected && sort_reverse != "true" ? {sort_reverse: "true"} : {})) 36 | %th{class: "header pjax #{column[:css_class]} #{sort_direction if selected}", :'data-href' => sort_location}= column[:link_text] 37 | %tbody 38 | - @history.each_with_index do |object, index| 39 | %tr 40 | - unless object.created_at.nil? 41 | %td= l(object.created_at, format: :long, default: l(object.created_at, format: :long, locale: :en)) 42 | %td= object.username 43 | - if @general 44 | - if o = @abstract_model.get(object.item) 45 | - label = o.send(@abstract_model.config.object_label_method) 46 | - if show_action = action(:show, @abstract_model, o) 47 | %td= link_to(label, url_for(action: show_action.action_name, model_name: @abstract_model.to_param, id: o.id), class: 'pjax') 48 | - else 49 | %td= label 50 | - else 51 | %td= "#{@abstract_model.config.label} ##{object.item}" 52 | %td= object.message.in?(['delete', 'new']) ? t("admin.actions.#{object.message}.done").capitalize : object.message 53 | %td= link_to(t("admin.history_rollback.table_headers.view_changes"), "#", class: "changeset", :data => {:url => url_for(action: action(:history_index, @abstract_model).action_name, model_name: @abstract_model.to_param, version_id: object.version_id)}) 54 | 55 | - unless params[:all] || !@history.respond_to?(:current_page) 56 | = paginate(@history, theme: lookup_context.exists?('kaminari/ra-twitter-bootstrap/_paginator') ? 'ra-twitter-bootstrap' : 'twitter-bootstrap', remote: true) 57 | = link_to(t("admin.misc.show_all"), send(path_method, params.merge(all: true)), class: "show-all btn pjax") unless (tc = @history.total_count) <= @history.size || tc > 100 58 | 59 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This command will automatically be run when you run "rails" with Rails 4 gems installed from the root of your application. 3 | 4 | ENGINE_ROOT = File.expand_path('../..', __FILE__) 5 | ENGINE_PATH = File.expand_path('../../lib/rails_admin_history_rollback/engine', __FILE__) 6 | 7 | # Set up gems listed in the Gemfile. 8 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 9 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) 10 | 11 | require 'rails/all' 12 | require 'rails/engine/commands' 13 | -------------------------------------------------------------------------------- /config/locales/history_rollback.en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | admin: 3 | history_rollback: 4 | cancel: "Cancel" 5 | confirm: "Are you sure?" 6 | table_headers: 7 | changes: "Changes" 8 | field: "Field" 9 | rollback: "Rollback" 10 | view_changes: "View changes" 11 | rollback_destroy: "Rolled back newly-created record by destroying it." 12 | rollback_success: "Rolled back changes to this record." 13 | rollback_impossible: "Couldn't rollback. Sorry." 14 | version_not_found: "Version does not exist." 15 | rollback_violates_foreign_key: "Couldn't rollback: this model links to another model, which doesn't exists." 16 | -------------------------------------------------------------------------------- /config/locales/history_rollback.ru.yml: -------------------------------------------------------------------------------- 1 | ru: 2 | admin: 3 | history_rollback: 4 | cancel: "Отмена" 5 | confirm: "Вы уверены?" 6 | table_headers: 7 | changes: "Изменения" 8 | field: "Поле" 9 | rollback: "Восстановить" 10 | view_changes: "Посмотреть изменения" 11 | rollback_destroy: "Данная версия восстановлена." 12 | rollback_success: "Изменения данной версии восстановлены." 13 | rollback_impossible: "Невозможно восстановить. Извините." 14 | version_not_found: "Данная версия не существует." 15 | rollback_violates_foreign_key: "Невозможно восстановить: эта модель ссылается на другую модель, которой не существует." 16 | -------------------------------------------------------------------------------- /config/locales/history_rollback.zh_cn.yml: -------------------------------------------------------------------------------- 1 | zh_cn: 2 | admin: 3 | history_rollback: 4 | cancel: "取消" 5 | confirm: "确定要还原?" 6 | table_headers: 7 | changes: "变化" 8 | field: "字段" 9 | rollback: "还原" 10 | view_changes: "查看" 11 | rollback_destroy: "Rolled back newly-created record by destroying it." 12 | rollback_success: "Rolled back changes to this record." 13 | rollback_impossible: "Couldn't rollback. Sorry." 14 | version_not_found: "Version does not exist." 15 | rollback_violates_foreign_key: "Couldn't rollback: this model links to another model, which doesn't exists." 16 | -------------------------------------------------------------------------------- /config/locales/pt-BR.yml: -------------------------------------------------------------------------------- 1 | pt-BR: 2 | admin: 3 | history_rollback: 4 | cancel: "Cancelar" 5 | confirm: "Deseja continuar?" 6 | table_headers: 7 | changes: "Mudanças" 8 | field: "Campo" 9 | rollback: "Desfazer mudanças" 10 | view_changes: "Ver mudanças" 11 | rollback_destroy: "Mudanças desfeitas no objeto recém criado. Objeto apagado." 12 | rollback_success: "Mudanças desfeitas neste objeto." 13 | rollback_impossible: "Não foi possível desfazer as mudanças." 14 | version_not_found: "Versão não existe." 15 | rollback_violates_foreign_key: "Não foi possível desfazer mudanças: este modelo está ligado a outro, que não existe." 16 | -------------------------------------------------------------------------------- /lib/rails_admin_history_rollback.rb: -------------------------------------------------------------------------------- 1 | require "rails_admin_history_rollback/engine" 2 | 3 | module RailsAdminHistoryRollback 4 | end 5 | 6 | require 'rails_admin/config/actions' 7 | require 'rails_admin/extension' 8 | require 'rails_admin/extensions/paper_trail' 9 | 10 | require "rails_admin_history_rollback/extensions/paper_trail/auditing_adapter" 11 | require "rails_admin_history_rollback/config/actions/history_index" 12 | -------------------------------------------------------------------------------- /lib/rails_admin_history_rollback/config/actions/history_index.rb: -------------------------------------------------------------------------------- 1 | module RailsAdmin 2 | module Config 3 | module Actions 4 | class HistoryIndex < Base 5 | RailsAdmin::Config::Actions.register(self) 6 | 7 | register_instance_option :authorization_key do 8 | :history 9 | end 10 | 11 | register_instance_option :collection do 12 | true 13 | end 14 | 15 | register_instance_option :http_methods do 16 | [:get, :put] # NEW / ROLLBACK 17 | end 18 | 19 | register_instance_option :route_fragment do 20 | 'history' 21 | end 22 | 23 | register_instance_option :controller do 24 | proc do 25 | @general = true 26 | @history = @auditing_adapter && @auditing_adapter.listing_for_model(@abstract_model, params[:query], params[:sort], params[:sort_reverse], params[:all], params[:page]) || [] 27 | version_class = @abstract_model.model.paper_trail_options.dig(:versions, :class_name).try(:constantize) || ::PaperTrail::Version 28 | @version = version_class.find(params[:version_id]) if params[:version_id] rescue false 29 | 30 | if request.get? # SHOW 31 | 32 | if @version 33 | render partial: 'version', layout: false 34 | else 35 | render @action.template_name 36 | end 37 | 38 | elsif request.put? # ROLLBACK 39 | begin 40 | if @version.event == "create" 41 | @record = @version.item_type.constantize.find(@version.item_id) 42 | @result = @record.destroy 43 | else 44 | @record = @version.reify 45 | @result = @record.save 46 | end 47 | 48 | if @result 49 | if @version.event == "create" 50 | flash[:success] = t 'admin.history_rollback.rollback_destroy' 51 | else 52 | flash[:success] = t 'admin.history_rollback.rollback_success' 53 | end 54 | else 55 | flash[:error] = t 'admin.history_rollback.rollback_impossible' 56 | end 57 | rescue ActiveRecord::RecordNotFound 58 | flash[:error] = t 'admin.history_rollback.version_not_found' 59 | redirect_to :action => :history_index 60 | rescue ActiveRecord::InvalidForeignKey 61 | flash[:error] = t 'admin.history_rollback.rollback_violates_foreign_key' 62 | end 63 | 64 | redirect_to :action => :history_index 65 | end 66 | end 67 | end 68 | 69 | register_instance_option :template_name do 70 | :history 71 | end 72 | 73 | register_instance_option :link_icon do 74 | 'icon-book' 75 | end 76 | end 77 | end 78 | end 79 | end 80 | -------------------------------------------------------------------------------- /lib/rails_admin_history_rollback/engine.rb: -------------------------------------------------------------------------------- 1 | module RailsAdminHistoryRollback 2 | class Engine < ::Rails::Engine 3 | initializer "RailsAdminHistoryRollback precompile hook" do |app| 4 | app.config.assets.precompile += [ 5 | 'rails_admin/diff_match_patch.js', 6 | 'rails_admin/jquery.pretty-text-diff.js', 7 | 'rails_admin/ra.history.js', 8 | 'rails_admin/ra.history.css' 9 | ] 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /lib/rails_admin_history_rollback/extensions/paper_trail/auditing_adapter.rb: -------------------------------------------------------------------------------- 1 | module RailsAdmin 2 | module Extensions 3 | module PaperTrail 4 | class VersionProxy 5 | def message 6 | @message = @version.event 7 | end 8 | def version_id 9 | @version.id 10 | end 11 | end 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /lib/rails_admin_history_rollback/version.rb: -------------------------------------------------------------------------------- 1 | module RailsAdminHistoryRollback 2 | VERSION = "1.0.2".freeze 3 | end 4 | -------------------------------------------------------------------------------- /rails_admin_history_rollback.gemspec: -------------------------------------------------------------------------------- 1 | $:.push File.expand_path("../lib", __FILE__) 2 | 3 | # Maintain your gem's version: 4 | require "rails_admin_history_rollback/version" 5 | 6 | # Describe your gem and declare its dependencies: 7 | Gem::Specification.new do |s| 8 | s.name = "rails_admin_history_rollback" 9 | s.version = RailsAdminHistoryRollback::VERSION 10 | s.authors = ["Rikki Pitt"] 11 | s.email = ["rikkipitt@gmail.com"] 12 | s.homepage = "https://github.com/rikkipitt/rails_admin_history_rollback" 13 | s.summary = "History rollback with paper_trail for rails_admin" 14 | s.description = "Enables users to rollback to any history version recorded by paper_trail. Versions are graphically diff'ed to help with rolling back." 15 | s.license = "MIT" 16 | 17 | s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] 18 | 19 | s.add_dependency "rails", ">= 4.2.0" 20 | s.add_dependency "rails_admin", ">= 0.6.6" 21 | s.add_dependency "paper_trail", ">= 3.0.6" 22 | end 23 | -------------------------------------------------------------------------------- /screenshots/history.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jemcode/rails_admin_history_rollback/c39e336e0aba75a4059dbf695b9d3d89628b7144/screenshots/history.png -------------------------------------------------------------------------------- /screenshots/modal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jemcode/rails_admin_history_rollback/c39e336e0aba75a4059dbf695b9d3d89628b7144/screenshots/modal.png --------------------------------------------------------------------------------