redactor_rails 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9188440b6b01ebef594f358bd90c9cba22857b4d
4
+ data.tar.gz: d48c7990d4a11a393e075effc04db249c3707db4
5
+ SHA512:
6
+ metadata.gz: 75eff331d943ff1cb8fdee1f4bb8a34486081b81ba8b2d116074c08c8f78f19c13fd2b211cec6f8541310b55a21d46ca45644c9ded4e3f6d01c642692f4930f3
7
+ data.tar.gz: 66bb7fd3611493bec6163151c262566e2262eaf6dbe24a9c240dee25e0f2d508228488abcda1e6d7db6b6fab34bd4ce41a4d332ab179cab7c854654691c00d3b
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.2.4
5
+ before_install: gem install bundler -v 1.14.6
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at kb1990@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in redactor_rails.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 kbravi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,123 @@
1
+ # RedactorRails
2
+
3
+ Rails Integration for Redactor 2. This gem creates models, controllers and uploaders for picture/document uploads. It also generates a basic configuration file.
4
+
5
+ Note: This gem doesn't include the javascript and stylesheet files for redactor. Please visit the official [redactor site](https://imperavi.com/redactor/) to purchase the assets.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'redactor_rails'
13
+ ```
14
+
15
+ And then execute:
16
+ ```
17
+ $ bundle
18
+ ```
19
+
20
+ Or install it yourself as:
21
+ ```
22
+ $ gem install redactor_rails
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ### 1. Run generator
28
+
29
+ After installing the gem, run
30
+
31
+ ```
32
+ rails generate redactor_rails:install
33
+ ```
34
+
35
+ This will install the migration, model and uploader files to your application. Then run
36
+
37
+ ```
38
+ rake db:migrate
39
+ ```
40
+
41
+ ### 2. Download the asset files
42
+
43
+ Download from the official [redactor site](https://imperavi.com/redactor/) and place it in `app/assets/javascripts/redactor_rails/` folder. Then, include these in your application. You can skip these if you include all your assets using `require_tree .`
44
+
45
+
46
+ Add to your `application.js`:
47
+
48
+ ```
49
+ //= require_tree ./redactor-rails
50
+ ```
51
+
52
+ Add to your `application.css`:
53
+
54
+ ```
55
+ *= require_tree ./redactor-rails
56
+ ```
57
+
58
+ redactor requires jQuery. So, add that to your assets if you don't already
59
+
60
+ ### 3. Initialize Redactor
61
+
62
+ For each textarea that you want to use with Redactor, add the "redactor" class.
63
+
64
+ ```
65
+ <%= text_area_tag :editor, "", :id => "redactor", :rows => 40, :cols => 120 %>
66
+ ```
67
+
68
+ ### 4. Customize redactor
69
+
70
+ You can customize your redactor configuration in your `app/assets/javascripts/redactor_rails/config.js` file
71
+ Check out [the official docs](https://imperavi.com/redactor/docs/) for settings and API.
72
+
73
+ ### 5. Customize uploaders
74
+
75
+ The gem will create uploader files that will handle the upload using Carrierwave. Check out `app/uploaders/redactor_rails/` directory and modify the uploaders based on your needs. Refer [carrierwave docs](https://github.com/carrierwaveuploader/carrierwave) for instructions.
76
+
77
+ ### 6. Authenticate users
78
+ In order to authenticate users, just add this method to your application_controller.rb. The default (if this method is absent) will allow all users to upload content.
79
+
80
+ ```ruby
81
+ def redactor_authenticate_user!
82
+ return current_user.blank? # or something like this
83
+ end
84
+ ```
85
+
86
+ ### 7. Associate user_id to uploads
87
+ The table includes user_id column, and you can set the user with the following method.
88
+
89
+ ```ruby
90
+ def redactor_current_user
91
+ return current_user # or something like this
92
+ end
93
+ ```
94
+
95
+ If the above method is absent, the default is `redactor_current_user || current_user || current_resource_owner || nil`
96
+
97
+ ## Advanced
98
+
99
+ ### 1. Redactor Plugins
100
+ To use any of [redactor plugins](https://imperavi.com/redactor/plugins/), download them to your `app/assets/javascripts/redactor_rails` and modify the configuration in `config.js` to add plugin.
101
+
102
+ ### 2. Turbolinks
103
+ When your app uses turbolinks, it will cache the page, and so when you renavigate to that page using browser navigation, your redactor will exist but will not function.
104
+
105
+ ```
106
+ $(document).on("turbolinks:before-cache", function() {
107
+ $('.redactor').redactor('core.destroy');
108
+ });
109
+ ```
110
+
111
+ ## Credits
112
+
113
+ This gem was based on the [redactor-rails]() gem that was built for an earlier free version of redactor, and that gem was partially based on [ck-editor](https://github.com/galetahub/ckeditor) project
114
+
115
+ ## Contributing
116
+
117
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kbravi/redactor_rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
118
+
119
+
120
+ ## License
121
+
122
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
123
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,28 @@
1
+ class RedactorRails::DocumentsController < ApplicationController
2
+ before_action :require_user_authentication!
3
+
4
+ def create
5
+ @document = RedactorRails.document_model.new
6
+
7
+ file = params[:file]
8
+ @document.data = RedactorRails::Http.normalize_param(file, request)
9
+ @document.user_id = get_redactor_current_user.try(:id)
10
+ @document.assetable = get_redactor_current_user
11
+
12
+ if @document.save
13
+ render json: { url: @document.url, name: @document.filename, id: @document.id }
14
+ else
15
+ render json: { error: @document.errors, message: @document.errors.full_messages.join(', ') }
16
+ end
17
+ end
18
+
19
+ private
20
+
21
+ def require_user_authentication!
22
+ (self.respond_to?(:redactor_authenticate_user!) && self.send(:redactor_authenticate_user!)) || true
23
+ end
24
+
25
+ def get_redactor_current_user
26
+ (self.respond_to?(:redactor_current_user) && self.send(:redactor_current_user)) || (self.respond_to?(:current_user) && self.current_user) || (self.respond_to?(:current_resource_owner, true) && self.send(:current_resource_owner)) || nil
27
+ end
28
+ end
@@ -0,0 +1,28 @@
1
+ class RedactorRails::PicturesController < ApplicationController
2
+ before_action :require_user_authentication!
3
+
4
+ def create
5
+ @picture = RedactorRails.picture_model.new
6
+
7
+ file = params[:file]
8
+ @picture.data = nil#RedactorRails::Http.normalize_param(file, request)
9
+ @picture.user_id = get_redactor_current_user.try(:id)
10
+ @picture.assetable = get_redactor_current_user
11
+
12
+ if @picture.save
13
+ render json: { url: @picture.url(:content), id: @picture.id }
14
+ else
15
+ render json: { error: @picture.errors, message: @picture.errors.full_messages.join(', ') }
16
+ end
17
+ end
18
+
19
+ private
20
+
21
+ def require_user_authentication!
22
+ (self.respond_to?(:redactor_authenticate_user!) && self.send(:redactor_authenticate_user!)) || true
23
+ end
24
+
25
+ def get_redactor_current_user
26
+ (self.respond_to?(:redactor_current_user) && self.send(:redactor_current_user)) || (self.respond_to?(:current_user) && self.current_user) || (self.respond_to?(:current_resource_owner, true) && self.send(:current_resource_owner)) || nil
27
+ end
28
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "redactor_rails"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/config/routes.rb ADDED
@@ -0,0 +1,10 @@
1
+ Rails.application.routes.draw do
2
+ mount RedactorRails::Engine => "/" if RedactorRails.mount
3
+ end
4
+
5
+ RedactorRails::Engine.routes.draw do
6
+ scope module: "redactor_rails" do
7
+ post '/redactor_rails/pictures', :to => 'pictures#create'
8
+ post '/redactor_rails/documents', :to => 'documents#create'
9
+ end
10
+ end
@@ -0,0 +1,68 @@
1
+ # taken from https://github.com/collectiveidea/audited/blob/master/lib/generators/audited/install_generator.rb
2
+ require 'rails/generators'
3
+ require 'rails/generators/migration'
4
+ require "active_record"
5
+ require "rails/generators/active_record"
6
+
7
+ module RedactorRails
8
+ module Generators
9
+ class InstallGenerator < ::Rails::Generators::Base
10
+ include ::Rails::Generators::Migration
11
+ source_root File.expand_path("../templates", __FILE__)
12
+
13
+ def self.next_migration_number(dirname)
14
+ Time.now.strftime("%Y%m%d%H%M%S")
15
+ end
16
+
17
+ # Implement the required interface for Rails::Generators::Migration.
18
+ def self.next_migration_number(dirname) #:nodoc:
19
+ next_migration_number = current_migration_number(dirname) + 1
20
+ if ::ActiveRecord::Base.timestamped_migrations
21
+ [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % next_migration_number].max
22
+ else
23
+ "%.3d" % next_migration_number
24
+ end
25
+ end
26
+
27
+ def copy_migration
28
+ @database = options["database"] || detect_database
29
+ unless @database.in?([nil, "postgresql", "postgresql-jsonb", "mysql", "sqlite"])
30
+ raise Thor::Error, "Unknown database option"
31
+ end
32
+ migration_template "active_record_redactor_assets_migration.rb", "db/migrate/create_redactor_assets.rb", migration_version: migration_version
33
+ end
34
+
35
+
36
+ def generate_model
37
+ [:asset, :picture, :document].each do |filename|
38
+ template "active_record_models/#{filename}.rb",
39
+ File.join('app/models', 'redactor_rails', "#{filename}.rb")
40
+ end
41
+
42
+ [:picture, :document].each do |filename|
43
+ template "uploaders/redactor_rails_#{filename}_uploader.rb",
44
+ File.join("app/uploaders", 'redactor_rails', "#{filename}_uploader.rb")
45
+ end
46
+ end
47
+
48
+ def create_config
49
+ template "config.js", File.join('app/assets/javascripts/redactor_rails', "config.js")
50
+ end
51
+
52
+ def detect_database
53
+ postgresql_version = ActiveRecord::Base.connection.send(:postgresql_version) rescue 0
54
+ if postgresql_version >= 90400
55
+ "postgresql-jsonb"
56
+ elsif postgresql_version >= 90200
57
+ "postgresql"
58
+ end
59
+ end
60
+
61
+ def migration_version
62
+ if ActiveRecord::VERSION::MAJOR >= 5
63
+ "[#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}]"
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,5 @@
1
+ class RedactorRails::Asset < ActiveRecord::Base
2
+ include RedactorRails::AssetBase
3
+ delegate :url, :current_path, :size, :content_type, :filename, :to => :data
4
+ validates_presence_of :data
5
+ end
@@ -0,0 +1,11 @@
1
+ class RedactorRails::Document < RedactorRails::Asset
2
+ mount_uploader :data, RedactorRails::DocumentUploader, :mount_on => :data_file_name
3
+
4
+ def url_content
5
+ url(:content)
6
+ end
7
+
8
+ def as_json_methods
9
+ [:image]
10
+ end
11
+ end
@@ -0,0 +1,7 @@
1
+ class RedactorRails::Picture < RedactorRails::Asset
2
+ mount_uploader :data, RedactorRails::PictureUploader, :mount_on => :data_file_name
3
+
4
+ def url_content
5
+ url(:content)
6
+ end
7
+ end
@@ -0,0 +1,28 @@
1
+ class <%= migration_class_name %> < ActiveRecord::Migration<%= migration_version %>
2
+ def self.up
3
+ create_table :redactor_assets do |t|
4
+ t.integer :user_id
5
+ t.string :data_file_name, :null => false
6
+ t.string :data_content_type
7
+ t.integer :data_file_size
8
+
9
+ t.integer :assetable_id
10
+ t.string :assetable_type, :limit => 30
11
+ t.string :type, :limit => 30
12
+
13
+ # Uncomment it to save images dimensions, if your need it
14
+ t.integer :width
15
+ t.integer :height
16
+
17
+ t.timestamps
18
+ end
19
+
20
+ add_index "redactor_assets", ["assetable_type", "type", "assetable_id"], :name => "idx_redactor_assetable_type"
21
+ add_index "redactor_assets", ["assetable_type", "assetable_id"], :name => "idx_redactor_assetable"
22
+ end
23
+
24
+ def self.down
25
+ drop_table :redactor_assets
26
+ end
27
+ end
28
+
@@ -0,0 +1,79 @@
1
+ window.init_redactor = function(){
2
+ var csrf_token = $('meta[name=csrf-token]').attr('content');
3
+ var csrf_param = $('meta[name=csrf-param]').attr('content');
4
+ var params = {};
5
+ if (csrf_param !== undefined && csrf_token !== undefined) {
6
+ params[csrf_param] = csrf_token;
7
+ }
8
+ $('#redactor').redactor({
9
+ // You can specify, which ones plugins you need.
10
+ // If you want to use plugins, you have download fils and add plugins to your
11
+ // application.js and application.css files and uncomment the line below:
12
+ // "plugins": ['fontsize', 'fontcolor', 'fontfamily', 'fullscreen', 'textdirection', 'clips'],
13
+ "imageUpload":"/redactor_rails/pictures",
14
+ "imageUploadFields": params,
15
+ "imageGetJson":"/redactor_rails/pictures",
16
+ "fileUpload":"/redactor_rails/documents",
17
+ "fileUploadFields": params,
18
+ "fileGetJson":"/redactor_rails/documents",
19
+ "path":"/assets/redactor_rails"
20
+ });
21
+ }
22
+
23
+ $(document).ready(window.init_redactor);
24
+
25
+ $(document).on("turbolinks:before-cache", function() {
26
+ $('.redactor').redactor('core.destroy');
27
+ });
28
+
29
+ // // Advanced Example to set redactor globally on the class ".redactor"
30
+ // window.init_redactor = function (){
31
+ // var csrf_token = $('meta[name=csrf-token]').attr('content');
32
+ // var csrf_param = $('meta[name=csrf-param]').attr('content');
33
+ // var params = {};
34
+ // if (csrf_param !== undefined && csrf_token !== undefined) {
35
+ // params[csrf_param] = csrf_token;
36
+ // }
37
+ // $('.redactor').not('.redactored').each(function(){
38
+ // var minHeight = parseInt($(this).css('min-height'));
39
+ // var maxHeight = parseInt($(this).css('max-height'));
40
+ // $(this).addClass('redactored');
41
+ // $(this).redactor({
42
+ // imageUpload:"/redactor_rails/pictures",
43
+ // imageUploadFields: params,
44
+ // imageGetJson:"/redactor_rails/pictures",
45
+ // fileUpload:"/redactor_rails/documents",
46
+ // fileUploadFields: params,
47
+ // fileGetJson:"/redactor_rails/documents",
48
+ // path:"/assets/redactor_rails",
49
+ // minHeight:minHeight,
50
+ // maxHeight:maxHeight,
51
+ // buttons : ['formatting', 'bold', 'italic', 'deleted', 'unorderedlist', 'orderedlist', 'outdent', 'indent', 'table', 'link', 'video', 'image', 'file', 'alignleft', 'aligncenter', 'alignright', 'justify', 'horizontalrule'],
52
+ // convertVideoLinks: true,
53
+ // convertImageLinks: true,
54
+ // plugins: ['fullscreen', 'video'],
55
+ // callbacks: {
56
+ // keyup: function(e){
57
+ // console.log(this.code.get().length);
58
+ // },
59
+ // imageUploadError: function(json){
60
+ // console.log(json.error);
61
+ // console.log(json.message);
62
+ // },
63
+ // fileUploadError: function(json){
64
+ // console.log(json.error);
65
+ // console.log(json.message);
66
+ // }
67
+ // }
68
+ // });
69
+ // });
70
+ // }
71
+
72
+ // $(document).ready( window.init_redactor );
73
+ // $(document).ajaxSuccess(window.init_redactor);
74
+
75
+ // // When you have turbolinks enabled
76
+ // $(document).on("turbolinks:before-cache", function() {
77
+ // $('.redactor').redactor('core.destroy');
78
+ // $('.redactor').removeClass('redactored');
79
+ // });
@@ -0,0 +1,15 @@
1
+ # encoding: utf-8
2
+ class RedactorRails::DocumentUploader < CarrierWave::Uploader::Base
3
+ include RedactorRails::UploaderBase
4
+
5
+ # storage :fog
6
+ storage :file
7
+
8
+ def store_dir
9
+ "system/redactor_assets/documents/#{model.id}"
10
+ end
11
+
12
+ def extension_white_list
13
+ RedactorRails.document_file_types
14
+ end
15
+ end
@@ -0,0 +1,31 @@
1
+ # encoding: utf-8
2
+ class RedactorRails::PictureUploader < CarrierWave::Uploader::Base
3
+ include RedactorRails::UploaderBase
4
+ include CarrierWave::MiniMagick
5
+
6
+ # Choose what kind of storage to use for this uploader:
7
+ storage :file
8
+
9
+ # Override the directory where uploaded files will be stored.
10
+ # This is a sensible default for uploaders that are meant to be mounted:
11
+ def store_dir
12
+ "system/redactor_assets/pictures/#{model.id}"
13
+ end
14
+
15
+ process :read_dimensions
16
+
17
+ # Create different versions of your uploaded files:
18
+ version :thumb do
19
+ process :resize_to_fill => [118, 100]
20
+ end
21
+
22
+ version :content do
23
+ process :resize_to_limit => [800, 800]
24
+ end
25
+
26
+ # Add a white list of extensions which are allowed to be uploaded.
27
+ # For images you might use something like this:
28
+ def extension_white_list
29
+ RedactorRails.image_file_types
30
+ end
31
+ end
@@ -0,0 +1,55 @@
1
+ module RedactorRails
2
+ module AssetBase
3
+ def self.included(base)
4
+ base.send(:include, InstanceMethods)
5
+ base.send(:extend, ClassMethods)
6
+ end
7
+
8
+ module ClassMethods
9
+ def self.extended(base)
10
+ base.class_eval do
11
+ self.table_name = "redactor_assets"
12
+
13
+ belongs_to :assetable, :polymorphic => true
14
+
15
+ if defined?(ActiveModel::ForbiddenAttributesProtection) && base.ancestors.include?(ActiveModel::ForbiddenAttributesProtection)
16
+ # Ok
17
+ elsif defined?(ActiveModel::MassAssignmentSecurity) && base.ancestors.include?(ActiveModel::MassAssignmentSecurity)
18
+ attr_accessible :data, :assetable_type, :assetable_id, :assetable
19
+ end
20
+ end
21
+ end
22
+ end
23
+
24
+ module InstanceMethods
25
+ def has_dimensions?
26
+ respond_to?(:width) && respond_to?(:height)
27
+ end
28
+
29
+ def image?
30
+ RedactorRails::IMAGE_TYPES.include?(data_content_type)
31
+ end
32
+
33
+ def image
34
+ url
35
+ end
36
+
37
+ def thumb
38
+ url(:thumb)
39
+ end
40
+
41
+ def as_json_methods
42
+ [:image, :thumb]
43
+ end
44
+
45
+ def as_json(options = nil)
46
+ options = {
47
+ :methods => as_json_methods,
48
+ :root => false
49
+ }
50
+
51
+ super options
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,4 @@
1
+ module RedactorRails
2
+ class Engine < Rails::Engine
3
+ end
4
+ end
@@ -0,0 +1,89 @@
1
+ # encoding: utf-8
2
+ require 'digest/sha1'
3
+ require 'mime/types'
4
+
5
+ module RedactorRails
6
+ module Http
7
+ # Create tempfile from hash
8
+ class UploadedFile
9
+ attr_accessor :original_filename, :content_type, :tempfile, :headers
10
+
11
+ def initialize(hash)
12
+ @original_filename = hash[:filename]
13
+ @content_type = hash[:type]
14
+ @headers = hash[:head]
15
+ @tempfile = hash[:tempfile]
16
+ raise(ArgumentError, ':tempfile is required') unless @tempfile
17
+ end
18
+
19
+ def open
20
+ @tempfile.open
21
+ end
22
+
23
+ def path
24
+ @tempfile.path
25
+ end
26
+
27
+ def read(*args)
28
+ @tempfile.read(*args)
29
+ end
30
+
31
+ def rewind
32
+ @tempfile.rewind
33
+ end
34
+
35
+ def size
36
+ @tempfile.size
37
+ end
38
+ end
39
+
40
+ # Usage (paperclip example)
41
+ # @asset.data = QqFile.new(params[:qqfile], request)
42
+ class QqFile < ::Tempfile
43
+
44
+ def initialize(filename, request, tmpdir = Dir::tmpdir)
45
+ @original_filename = filename
46
+ @request = request
47
+
48
+ super Digest::SHA1.hexdigest(filename), tmpdir
49
+ fetch
50
+ end
51
+
52
+ def fetch
53
+ self.write(body)
54
+ self.rewind
55
+ self
56
+ end
57
+
58
+ def original_filename
59
+ @original_filename
60
+ end
61
+
62
+ def content_type
63
+ types = MIME::Types.type_for(original_filename)
64
+ types.empty? ? @request.content_type : types.first.to_s
65
+ end
66
+
67
+ def body
68
+ if @request.raw_post.respond_to?(:force_encoding)
69
+ @request.raw_post.force_encoding("UTF-8")
70
+ else
71
+ @request.raw_post
72
+ end
73
+ end
74
+ end
75
+
76
+ # Convert nested Hash to HashWithIndifferentAccess and replace
77
+ # file upload hash with UploadedFile objects
78
+ def self.normalize_param(*args)
79
+ value = args.first
80
+ if Hash === value && value.has_key?(:tempfile)
81
+ UploadedFile.new(value)
82
+ elsif value.is_a?(String)
83
+ QqFile.new(*args)
84
+ else
85
+ value
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,62 @@
1
+ require 'mime/types'
2
+ require 'mini_magick'
3
+
4
+ module RedactorRails
5
+ module UploaderBase
6
+ def self.included(base)
7
+ base.send(:include, InstanceMethods)
8
+ base.send(:extend, ClassMethods)
9
+ end
10
+
11
+ module ClassMethods
12
+ def self.extended(base)
13
+ base.class_eval do
14
+ process :extract_content_type
15
+ process :set_size
16
+ end
17
+ end
18
+ end
19
+
20
+ module InstanceMethods
21
+ # process :strip
22
+ def strip
23
+ manipulate! do |img|
24
+ img.strip
25
+ img = yield(img) if block_given?
26
+ img
27
+ end
28
+ end
29
+
30
+ # process :quality => 85
31
+ def quality(percentage)
32
+ manipulate! do |img|
33
+ img.quality(percentage)
34
+ img = yield(img) if block_given?
35
+ img
36
+ end
37
+ end
38
+
39
+ def extract_content_type
40
+ if file.content_type == 'application/octet-stream' || file.content_type.blank?
41
+ content_type = MIME::Types.type_for(original_filename).first
42
+ else
43
+ content_type = file.content_type
44
+ end
45
+
46
+ model.data_content_type = content_type.to_s
47
+ end
48
+
49
+ def set_size
50
+ model.data_file_size = file.size
51
+ end
52
+
53
+ def read_dimensions
54
+ if model.image? && model.has_dimensions?
55
+ magick = ::MiniMagick::Image.new(current_path)
56
+ model.width, model.height = magick[:width], magick[:height]
57
+ end
58
+ end
59
+
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,3 @@
1
+ module RedactorRails
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,27 @@
1
+ require "redactor_rails/engine"
2
+ require "redactor_rails/http"
3
+ require "redactor_rails/asset_base"
4
+ require "redactor_rails/uploader_base"
5
+ require "redactor_rails/version"
6
+ require 'carrierwave'
7
+
8
+ module RedactorRails
9
+ IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/pjpeg', 'image/tiff', 'image/x-png']
10
+
11
+ FILE_TYPES = ['application/msword', 'application/pdf', 'text/plain', 'text/rtf', 'application/vnd.ms-excel']
12
+
13
+ mattr_accessor :mount
14
+ self.mount = true
15
+
16
+ mattr_accessor :image_file_types, :document_file_types
17
+ @@image_file_types = ["jpg", "jpeg", "png", "gif", "tiff"]
18
+ @@document_file_types = ["pdf", "doc", "docx", "xls", "xlsx", "rtf", "txt"]
19
+
20
+ def self.picture_model
21
+ RedactorRails::Picture
22
+ end
23
+
24
+ def self.document_model
25
+ RedactorRails::Document
26
+ end
27
+ end
@@ -0,0 +1,30 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'redactor_rails/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "redactor_rails"
8
+ spec.version = RedactorRails::VERSION
9
+ spec.authors = ["Karthik Ravichandran"]
10
+ spec.email = ["kb1990@gmail.com"]
11
+
12
+ spec.summary = %q{Integrates asset uploaders with the redactor editor}
13
+ spec.homepage = "https://github.com/kbravi/redactor_rails"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
17
+ f.match(%r{^(test|spec|features)/})
18
+ end
19
+ spec.bindir = "exe"
20
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_dependency("carrierwave")
24
+ spec.add_dependency("mini_magick")
25
+ spec.add_dependency("mime-types")
26
+
27
+ spec.add_development_dependency "bundler", "~> 1.14"
28
+ spec.add_development_dependency "rake", "~> 10.0"
29
+ spec.add_development_dependency "rspec", "~> 3.0"
30
+ end
metadata ADDED
@@ -0,0 +1,156 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: redactor_rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Karthik Ravichandran
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-07-14 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: carrierwave
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: mini_magick
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: mime-types
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.14'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.14'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '10.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '10.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '3.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '3.0'
97
+ description:
98
+ email:
99
+ - kb1990@gmail.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".gitignore"
105
+ - ".rspec"
106
+ - ".travis.yml"
107
+ - CODE_OF_CONDUCT.md
108
+ - Gemfile
109
+ - LICENSE.txt
110
+ - README.md
111
+ - Rakefile
112
+ - app/controller/redactor_rails/documents_controller.rb
113
+ - app/controller/redactor_rails/pictures_controller.rb
114
+ - bin/console
115
+ - bin/setup
116
+ - config/routes.rb
117
+ - lib/generators/redactor_rails/install_generator.rb
118
+ - lib/generators/redactor_rails/templates/active_record_models/asset.rb
119
+ - lib/generators/redactor_rails/templates/active_record_models/document.rb
120
+ - lib/generators/redactor_rails/templates/active_record_models/picture.rb
121
+ - lib/generators/redactor_rails/templates/active_record_redactor_assets_migration.rb
122
+ - lib/generators/redactor_rails/templates/config.js
123
+ - lib/generators/redactor_rails/templates/uploaders/redactor_rails_document_uploader.rb
124
+ - lib/generators/redactor_rails/templates/uploaders/redactor_rails_picture_uploader.rb
125
+ - lib/redactor_rails.rb
126
+ - lib/redactor_rails/asset_base.rb
127
+ - lib/redactor_rails/engine.rb
128
+ - lib/redactor_rails/http.rb
129
+ - lib/redactor_rails/uploader_base.rb
130
+ - lib/redactor_rails/version.rb
131
+ - redactor_rails.gemspec
132
+ homepage: https://github.com/kbravi/redactor_rails
133
+ licenses:
134
+ - MIT
135
+ metadata: {}
136
+ post_install_message:
137
+ rdoc_options: []
138
+ require_paths:
139
+ - lib
140
+ required_ruby_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ required_rubygems_version: !ruby/object:Gem::Requirement
146
+ requirements:
147
+ - - ">="
148
+ - !ruby/object:Gem::Version
149
+ version: '0'
150
+ requirements: []
151
+ rubyforge_project:
152
+ rubygems_version: 2.4.8
153
+ signing_key:
154
+ specification_version: 4
155
+ summary: Integrates asset uploaders with the redactor editor
156
+ test_files: []