autochthon 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,78 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'erb'
2
4
  require 'json'
3
5
  require 'sinatra/base'
6
+ require_relative 'configuration'
4
7
 
5
8
  module Autochthon
6
9
  class Web < Sinatra::Base
7
- enable :sessions
8
-
9
10
  set :root, File.expand_path(File.dirname(__FILE__) + "/../..")
10
- set :views, "#{root}/public"
11
+ set :views, "#{root}/views"
12
+
13
+ # Under Rails the engine warns once at boot (after_initialize); plain Rack
14
+ # has no boot hook, so warn when the app is built (first request).
15
+ def self.new(*)
16
+ Autochthon.warn_if_unprotected unless defined?(Autochthon::Engine)
17
+ super
18
+ end
19
+
20
+ WRITE_METHODS = %w[POST PUT PATCH DELETE].freeze
21
+
22
+ # Every request passes the authorize hook; write requests must also be
23
+ # same-origin JSON, which a cross-site form or no-cors fetch cannot forge.
24
+ before do
25
+ halt 403 unless Autochthon.authorized?(request)
26
+ if WRITE_METHODS.include?(request.request_method)
27
+ halt 403 unless same_origin?
28
+ halt 415 unless request.media_type == 'application/json'
29
+ end
30
+ end
31
+
32
+ # Sec-Fetch-Site is set by the browser and cannot be forged by page
33
+ # script, so when present it decides; older clients fall back to Origin.
34
+ def same_origin?
35
+ fetch_site = request.get_header('HTTP_SEC_FETCH_SITE')
36
+
37
+ if fetch_site
38
+ fetch_site == 'same-origin'
39
+ else
40
+ request.get_header('HTTP_ORIGIN') == request.base_url
41
+ end
42
+ end
11
43
 
12
44
  def json
13
45
  @json ||= JSON.parse(request.body.read, symbolize_names: true)
46
+ rescue JSON::ParserError
47
+ halt_with_error 400, "the request body is not valid JSON"
48
+ end
49
+
50
+ def halt_with_error(status, message)
51
+ content_type :json
52
+ halt status, {error: message}.to_json
53
+ end
54
+
55
+ # The payload must be an object with a non-empty String locale and key
56
+ # and a String value; anything else is refused before reaching the backend.
57
+ def translation_params
58
+ halt_with_error 422, "the request body must be a JSON object" unless json.is_a?(Hash)
59
+
60
+ locale, key, value = json.values_at(:locale, :key, :value)
61
+ halt_with_error 422, "locale must be a non-empty String" unless present_string?(locale)
62
+ halt_with_error 422, "key must be a non-empty String" unless present_string?(key)
63
+ halt_with_error 422, "value must be a String" unless value.is_a?(String)
64
+
65
+ [locale, key, value]
66
+ end
67
+
68
+ def present_string?(object)
69
+ object.is_a?(String) && !object.empty?
14
70
  end
15
71
 
16
72
  def expand_translation(key, value)
17
- keys = key.split(I18n::Backend::Flatten::FLATTEN_SEPARATOR)
73
+ *keys, tail = key.split(I18n::Backend::Flatten::FLATTEN_SEPARATOR)
18
74
 
19
- keys[0...-1].reverse.inject(keys.last => value) do |out, k|
75
+ keys.reverse.inject(tail => value) do |out, k|
20
76
  {k => out}
21
77
  end
22
78
  end
@@ -34,22 +90,13 @@ module Autochthon
34
90
  post '/translations' do
35
91
  content_type :json
36
92
 
37
- Autochthon.backend.store_translations(json[:locale],
38
- expand_translation(json[:key], json[:value]),
39
- escape: false).to_json
40
- end
41
- end
42
- end
93
+ locale, key, value = translation_params
43
94
 
44
- if defined?(::ActionDispatch::Request::Session) &&
45
- !::ActionDispatch::Request::Session.respond_to?(:each)
46
- # mperham/sidekiq#2460
47
- # Rack apps can't reuse the Rails session store without
48
- # this monkeypatch
49
- class ActionDispatch::Request::Session
50
- def each(&block)
51
- hash = self.to_hash
52
- hash.each(&block)
95
+ Autochthon.backend.store_translations(
96
+ locale,
97
+ expand_translation(key, value),
98
+ escape: false
99
+ ).to_json
53
100
  end
54
101
  end
55
102
  end
data/lib/autochthon.rb CHANGED
@@ -1,28 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "i18n"
1
4
  require "autochthon/version"
5
+ require "autochthon/configuration"
2
6
  require "autochthon/web"
3
7
  require 'autochthon/engine'
4
8
  require 'autochthon/backend/simple'
5
9
  require 'autochthon/backend/active_record'
6
10
  require 'autochthon/backend/redis'
7
-
8
- module Autochthon
9
- module Methods
10
- def backend=(backend)
11
- @@backend = backend
12
- end
13
-
14
- def backend
15
- @@backend
16
- end
17
-
18
- def mount_point=(mount_point)
19
- @@mount_point = mount_point
20
- end
21
-
22
- def mount_point
23
- @@mount_point
24
- end
25
- end
26
-
27
- extend Methods
28
- end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+ require "rails/generators/active_record/migration"
5
+
6
+ module Autochthon
7
+ module Generators
8
+ # `rails g autochthon:install`: sets up the ActiveRecord backend.
9
+ # Rails only loads this file when the generator runs, so the gem itself
10
+ # does not depend on Rails.
11
+ class InstallGenerator < ::Rails::Generators::Base
12
+ include ::ActiveRecord::Generators::Migration
13
+
14
+ source_root File.expand_path("templates", __dir__)
15
+
16
+ desc "Creates the translations table migration, an initializer and a route for Autochthon"
17
+
18
+ def create_migration_file
19
+ migration_template "create_translations.rb.erb", File.join(db_migrate_path, "create_translations.rb")
20
+ end
21
+
22
+ def create_initializer
23
+ template "initializer.rb.erb", "config/initializers/autochthon.rb"
24
+ end
25
+
26
+ def mount_web
27
+ route 'mount Autochthon::Web => Autochthon.mount_point, as: "autochthon"'
28
+ end
29
+
30
+ def show_next_steps
31
+ say "\nNext: add `gem \"i18n-active_record\", \"~> 1.4\"` to your Gemfile (if missing), run `bin/rails db:migrate`, " \
32
+ "then `bin/rails autochthon:import` to copy your YAML translations into the database."
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,16 @@
1
+ class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
2
+ def change
3
+ create_table :translations do |t|
4
+ t.string :scope
5
+ t.string :locale
6
+ t.string :key
7
+ t.text :value
8
+ t.text :interpolations
9
+ t.boolean :is_proc, default: false
10
+
11
+ t.timestamps
12
+ end
13
+
14
+ add_index :translations, [:locale, :key]
15
+ end
16
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "i18n/backend/active_record"
4
+
5
+ # Translations edited in Autochthon are stored in the `translations` table.
6
+ Autochthon.backend = Autochthon::Backend::ActiveRecord.new
7
+
8
+ # Database translations win; YAML files fill in keys not yet in the database
9
+ # (run `bin/rails autochthon:import` to copy them over).
10
+ I18n.backend = I18n::Backend::Chain.new(Autochthon.backend, I18n::Backend::Simple.new)
11
+
12
+ # Path the Autochthon web app is mounted at (see config/routes.rb).
13
+ Autochthon.mount_point = "/autochthon"
14
+
15
+ # Who may use Autochthon. The callable receives the Rack request; a truthy
16
+ # result grants access. Without it, every request outside development and
17
+ # test gets 403. For example, with Devise:
18
+ #
19
+ # Autochthon.authorize = ->(request) { request.env["warden"]&.user&.admin? }
20
+ #
21
+ # Autochthon.authorize = ->(request) { false }
metadata CHANGED
@@ -1,71 +1,28 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: autochthon
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 1.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Adam Sokolnicki
8
- autorequire:
9
8
  bindir: exe
10
9
  cert_chain: []
11
- date: 2016-07-19 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
- - !ruby/object:Gem::Dependency
14
- name: bundler
15
- requirement: !ruby/object:Gem::Requirement
16
- requirements:
17
- - - "~>"
18
- - !ruby/object:Gem::Version
19
- version: '1.10'
20
- type: :development
21
- prerelease: false
22
- version_requirements: !ruby/object:Gem::Requirement
23
- requirements:
24
- - - "~>"
25
- - !ruby/object:Gem::Version
26
- version: '1.10'
27
- - !ruby/object:Gem::Dependency
28
- name: rake
29
- requirement: !ruby/object:Gem::Requirement
30
- requirements:
31
- - - "~>"
32
- - !ruby/object:Gem::Version
33
- version: '10.0'
34
- type: :development
35
- prerelease: false
36
- version_requirements: !ruby/object:Gem::Requirement
37
- requirements:
38
- - - "~>"
39
- - !ruby/object:Gem::Version
40
- version: '10.0'
41
12
  - !ruby/object:Gem::Dependency
42
13
  name: sinatra
43
14
  requirement: !ruby/object:Gem::Requirement
44
15
  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: sinatra-contrib
57
- requirement: !ruby/object:Gem::Requirement
58
- requirements:
59
- - - ">="
16
+ - - "~>"
60
17
  - !ruby/object:Gem::Version
61
- version: '0'
18
+ version: '4.0'
62
19
  type: :runtime
63
20
  prerelease: false
64
21
  version_requirements: !ruby/object:Gem::Requirement
65
22
  requirements:
66
- - - ">="
23
+ - - "~>"
67
24
  - !ruby/object:Gem::Version
68
- version: '0'
25
+ version: '4.0'
69
26
  - !ruby/object:Gem::Dependency
70
27
  name: i18n
71
28
  requirement: !ruby/object:Gem::Requirement
@@ -88,39 +45,30 @@ executables: []
88
45
  extensions: []
89
46
  extra_rdoc_files: []
90
47
  files:
91
- - ".gitignore"
92
- - Gemfile
48
+ - CHANGELOG.md
93
49
  - LICENSE.txt
94
50
  - README.md
95
- - Rakefile
96
- - autochthon.gemspec
97
- - bin/console
98
- - config.ru
99
51
  - lib/autochthon.rb
100
52
  - lib/autochthon/backend/active_record.rb
101
53
  - lib/autochthon/backend/fetching_all.rb
102
54
  - lib/autochthon/backend/redis.rb
103
55
  - lib/autochthon/backend/simple.rb
56
+ - lib/autochthon/configuration.rb
104
57
  - lib/autochthon/engine.rb
105
58
  - lib/autochthon/tasks/rails.rake
106
59
  - lib/autochthon/version.rb
107
60
  - lib/autochthon/web.rb
61
+ - lib/generators/autochthon/install/install_generator.rb
62
+ - lib/generators/autochthon/install/templates/create_translations.rb.erb
63
+ - lib/generators/autochthon/install/templates/initializer.rb.erb
108
64
  - public/bundle.js
109
- - public/index.erb
110
- - vendor/assets/javascripts/autochthon/application.js.erb
111
- - vendor/assets/javascripts/autochthon/autochthon.js
112
- - web/package.json
113
- - web/src/Dialog.jsx
114
- - web/src/Translations.jsx
115
- - web/src/callbacks.js
116
- - web/src/main.jsx
117
- - web/src/store.js
118
- - web/webpack.config.js
65
+ - views/index.erb
119
66
  homepage: https://github.com/asok/autochthon
120
67
  licenses:
121
68
  - MIT
122
- metadata: {}
123
- post_install_message:
69
+ metadata:
70
+ source_code_uri: https://github.com/asok/autochthon
71
+ changelog_uri: https://github.com/asok/autochthon/blob/master/CHANGELOG.md
124
72
  rdoc_options: []
125
73
  require_paths:
126
74
  - lib
@@ -128,17 +76,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
128
76
  requirements:
129
77
  - - ">="
130
78
  - !ruby/object:Gem::Version
131
- version: '0'
79
+ version: '3.3'
132
80
  required_rubygems_version: !ruby/object:Gem::Requirement
133
81
  requirements:
134
82
  - - ">="
135
83
  - !ruby/object:Gem::Version
136
84
  version: '0'
137
85
  requirements: []
138
- rubyforge_project:
139
- rubygems_version: 2.5.1
140
- signing_key:
86
+ rubygems_version: 4.0.20
141
87
  specification_version: 4
142
88
  summary: Sinatra app for managing I18n translations
143
89
  test_files: []
144
- has_rdoc:
data/.gitignore DELETED
@@ -1,14 +0,0 @@
1
- /.bundle/
2
- /.yardoc
3
- /Gemfile.lock
4
- /_yardoc/
5
- /coverage/
6
- /doc/
7
- /pkg/
8
- /spec/reports/
9
- /tmp/
10
- /web/node_modules/
11
- *.tern-port
12
- .ruby-version
13
- local
14
- capybara-*
data/Gemfile DELETED
@@ -1,22 +0,0 @@
1
- source 'https://rubygems.org'
2
-
3
- gem 'activerecord'
4
- gem 'actionview'
5
-
6
- gem 'i18n'
7
-
8
- gem 'i18n-active_record',
9
- :require => 'i18n/active_record'
10
-
11
- gem 'redis-i18n', '~> 0.6.5'
12
-
13
- group :test do
14
- gem "pry"
15
- gem "byebug"
16
- gem "sqlite3"
17
- gem "rspec"
18
- gem 'capybara-webkit'
19
- gem 'selenium-webdriver'
20
- end
21
-
22
- gemspec
data/Rakefile DELETED
@@ -1,6 +0,0 @@
1
- require "bundler/gem_tasks"
2
- require "rspec/core/rake_task"
3
-
4
- RSpec::Core::RakeTask.new(:spec)
5
-
6
- task :default => :spec
data/autochthon.gemspec DELETED
@@ -1,28 +0,0 @@
1
- # coding: utf-8
2
- lib = File.expand_path('../lib', __FILE__)
3
- $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
- require 'autochthon/version'
5
-
6
- Gem::Specification.new do |spec|
7
- spec.name = "autochthon"
8
- spec.version = Autochthon::VERSION
9
- spec.authors = ["Adam Sokolnicki"]
10
- spec.email = ["adam.sokolnicki@gmail.com"]
11
-
12
- spec.summary = %q{Sinatra app for managing I18n translations}
13
- spec.description = %q{Sinatra app for managing I18n translations stored in YAML files, database or Redis}
14
- spec.homepage = "https://github.com/asok/autochthon"
15
- spec.license = "MIT"
16
-
17
- spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
- spec.bindir = "exe"
19
- spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
- spec.require_paths = ["lib"]
21
-
22
- spec.add_development_dependency "bundler", "~> 1.10"
23
- spec.add_development_dependency "rake", "~> 10.0"
24
-
25
- spec.add_dependency "sinatra"
26
- spec.add_dependency "sinatra-contrib"
27
- spec.add_dependency "i18n"
28
- end
data/bin/console DELETED
@@ -1,7 +0,0 @@
1
- #!/usr/bin/env ruby
2
-
3
- require "bundler/setup"
4
- require "local"
5
-
6
- require "pry"
7
- Pry.start
data/config.ru DELETED
@@ -1,3 +0,0 @@
1
- require './lib/autochthon/web'
2
-
3
- run Autochthon::Web
@@ -1,3 +0,0 @@
1
- //= require ./autochthon
2
-
3
- window.Autochthon('<%= Autochthon.mount_point %>');
@@ -1,140 +0,0 @@
1
- window.Autochthon = function(mountPoint) {
2
- "use strict";
3
-
4
- var submit = function(e) {
5
- e.preventDefault();
6
-
7
- var toSend = e.data.toSend;
8
- toSend.value = $('#autochthon-value').val();
9
-
10
- $.ajax({
11
- url: e.data.url,
12
- type: e.data.type,
13
- data: JSON.stringify(toSend),
14
- dataType: 'json',
15
- contentType: 'application/json',
16
- headers: {
17
- 'HTTP_X_CSRF_TOKEN': $.rails.csrfToken()
18
- },
19
- success: function(response){
20
- modal().close();
21
- $(e.data.target).html(response[toSend.key]);
22
- highlight(e.data.target);
23
- },
24
- error: function(xhr, status, error) {
25
- console.error(xhr);
26
- }
27
- });
28
- };
29
-
30
- var highlight = function(el) {
31
- el = $(el);
32
- var colors = [
33
- el.css("backgroundColor"),
34
- "#fffff0",
35
- "#ffffd0",
36
- "#ffffe0",
37
- "#ffffd0",
38
- "#fffec0",
39
- "#fffdb0",
40
- "#fffca0",
41
- "#fffb90",
42
- "#fffa80"
43
- ];
44
-
45
- var id;
46
- var time = 100;
47
- var hl = function() {
48
- var color = colors.pop();
49
- if(color)
50
- el.css({backgroundColor: color});
51
- else
52
- clearInterval(id);
53
- };
54
-
55
- id = setInterval(hl, time);
56
- };
57
-
58
- var modal = function() {
59
- return $('#autochthon-modal')[0];
60
- };
61
-
62
- var form = function() {
63
- return "<form id='autochthon-form'>" +
64
- "<p id='autochthon-p'></p>" +
65
- "<textarea id='autochthon-value' name='value'></textarea>" +
66
- "</br>" +
67
- "<button id='autochthon-cancel' type='button'>Cancel</button>" +
68
- "<button id='autochthon-submit' type='submit'>Submit</button>" +
69
- "</form>";
70
- };
71
-
72
- var appendModal = function() {
73
- document.body.innerHTML += "<dialog id='autochthon-modal'>" +
74
- form() +
75
- "</dialog>";
76
- };
77
-
78
- var openForm = function(t) {
79
- var p = 'Update translation for locale: ' + t.locale + ' and key: ' + t.key;
80
-
81
- $('#autochthon-p').text(p);
82
- $('#autochthon-value').val(t.value);
83
- $('#autochthon-value').attr('placeholder', 'A new value for key: ' + t.key);
84
-
85
- modal().showModal();
86
- };
87
-
88
- var extractLocale = function(str) {
89
- return str.split('.')[0];
90
- };
91
-
92
- var extractKey = function(str) {
93
- var parts = str.split('.');
94
- return parts.splice(1, parts.length).join('.');
95
- };
96
-
97
- var contextListener = function() {
98
- $('#autochthon-cancel').on('click', function(e){
99
- modal().close();
100
- });
101
-
102
- $(document).on('contextmenu', function(e) {
103
- var el = e.target;
104
- if(el instanceof Element &&
105
- el.title &&
106
- el.title.match(/^translation missing/)){
107
-
108
- if (typeof HTMLDialogElement !== 'function') {
109
- alert("Your browser does not support the 'dialog' element");
110
- return;
111
- }
112
-
113
- var key = el.title.match(/^translation missing: (.+)$/)[1];
114
-
115
- openForm({
116
- value: el.textContent,
117
- locale: extractLocale(key),
118
- key: extractKey(key)
119
- });
120
-
121
- $('#autochthon-form').off().on('submit', {
122
- url: "/" + mountPoint + "/translations",
123
- type: 'POST',
124
- target: e.target,
125
- toSend: {
126
- key: extractKey(key),
127
- locale: extractLocale(key)
128
- }
129
- }, submit);
130
- e.preventDefault();
131
- }
132
- });
133
- };
134
-
135
- document.addEventListener('DOMContentLoaded', function() {
136
- appendModal();
137
- contextListener();
138
- $.rails.refreshCSRFTokens();
139
- });
140
- };
data/web/package.json DELETED
@@ -1,22 +0,0 @@
1
- {
2
- "name": "local",
3
- "version": "0.1.0",
4
- "dependencies": {
5
- "babel-core": "~4.4.3",
6
- "babel-loader": "~4.0.0",
7
- "css-loader": "~0.9.1",
8
- "react-router": "^0.13.0",
9
- "react-tap-event-plugin": "*",
10
- "restful-material": "asok/restful-material",
11
- "webpack": "~1.10.5",
12
- "material-ui": "0.14.0",
13
- "react": "*",
14
- "react-dom": "*",
15
- "react-intl": "2.0.0-beta-2"
16
- },
17
- "scripts": {
18
- "watch": "webpack --progress --colors --watch",
19
- "build": "ENV=production webpack -p"
20
- },
21
- "author": "asok"
22
- }
data/web/src/Dialog.jsx DELETED
@@ -1,61 +0,0 @@
1
- import React from "react";
2
- import { ActionDone } from "material-ui/lib/svg-icons";
3
- import { TextField, Dialog, FlatButton, RaisedButton } from "material-ui";
4
- import store from "./store";
5
- import callbacks from "./callbacks";
6
-
7
- module.exports = React.createClass({
8
- mixins: [callbacks],
9
-
10
- getInitialState() {
11
- return {
12
- open: false,
13
- translation: new Map()
14
- };
15
- },
16
-
17
- show(translation) {
18
- this.setState({
19
- translation: translation,
20
- open: true
21
- });
22
- },
23
-
24
- close(xhr) {
25
- this.setState({open: false});
26
- return xhr;
27
- },
28
-
29
- cb(xhr) {
30
- this.props.onSuccess();
31
- return xhr;
32
- },
33
-
34
- submit() {
35
- let t = this.state.translation;
36
- t.set('value', this.refs.field.getValue());
37
- store.update(t).then(this.onSuccess, this.onFailure).
38
- then(this.close).then(this.cb);
39
- },
40
-
41
- render() {
42
- return(
43
- <Dialog open={this.state.open} >
44
- <p>
45
- New value for key: {this.state.translation.get('key')}
46
- </p>
47
- <div>
48
- <TextField
49
- ref="field"
50
- multiLine={true}
51
- defaultValue={this.state.translation.get('value')} />
52
- </div>
53
-
54
- <div>
55
- <RaisedButton primary={false} label="Cancel" onClick={this.close} />
56
- <RaisedButton primary={true} label="OK" onClick={this.submit} />
57
- </div>
58
- </Dialog>
59
- );
60
- }
61
- });