kruczie 1.1.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.
Files changed (46) hide show
  1. checksums.yaml +7 -0
  2. data/README.md +138 -0
  3. data/config/locales/ru.yml +97 -0
  4. data/docs/api.md +390 -0
  5. data/docs/codeberg.md +88 -0
  6. data/docs/data-models.md +135 -0
  7. data/docs/implementation.md +106 -0
  8. data/docs/ngrams.md +82 -0
  9. data/docs/phrases-tones.md +204 -0
  10. data/docs/recovery.md +145 -0
  11. data/docs/release-0.2.2.md +7 -0
  12. data/lib/generators/kruczie/generator.rb +29 -0
  13. data/lib/generators/kruczie/migration/generator.rb +39 -0
  14. data/lib/generators/kruczie/model/generator.rb +27 -0
  15. data/lib/generators/kruczie/templates/app/controllers/neumos_controller.rb +59 -0
  16. data/lib/generators/kruczie/templates/app/models/description.rb +3 -0
  17. data/lib/generators/kruczie/templates/app/models/neum/ditty.rb +2 -0
  18. data/lib/generators/kruczie/templates/app/models/neum/element.rb +2 -0
  19. data/lib/generators/kruczie/templates/app/models/neum/exultee.rb +2 -0
  20. data/lib/generators/kruczie/templates/app/models/neum/note.rb +2 -0
  21. data/lib/generators/kruczie/templates/app/models/neum/secretlee.rb +2 -0
  22. data/lib/generators/kruczie/templates/app/models/neum/symbol.rb +2 -0
  23. data/lib/generators/kruczie/templates/app/models/neum/theta.rb +2 -0
  24. data/lib/generators/kruczie/templates/app/models/neum.rb +9 -0
  25. data/lib/generators/kruczie/templates/app/models/resource/volumen.rb +2 -0
  26. data/lib/generators/kruczie/templates/app/models/resource.rb +4 -0
  27. data/lib/generators/kruczie/templates/app/models/tag.rb +6 -0
  28. data/lib/generators/kruczie/templates/app/models/title.rb +2 -0
  29. data/lib/generators/kruczie/templates/create_descriptions.rb.erb +16 -0
  30. data/lib/generators/kruczie/templates/create_neumos.rb.erb +33 -0
  31. data/lib/generators/kruczie/templates/create_resources.rb.erb +21 -0
  32. data/lib/generators/kruczie/templates/create_tags.rb.erb +17 -0
  33. data/lib/generators/kruczie/templates/kruczie.yaml.erb +110 -0
  34. data/lib/generators/kruczie/templates/kruczie_server.yaml +86 -0
  35. data/lib/generators/kruczie/tiun/generator.rb +60 -0
  36. data/lib/kruczie/model/neum.rb +47 -0
  37. data/lib/kruczie/railtie.rb +11 -0
  38. data/lib/kruczie/services/import.rb +142 -0
  39. data/lib/kruczie/services/schema.rb +24 -0
  40. data/lib/kruczie/services/search.rb +83 -0
  41. data/lib/kruczie/services/text.rb +112 -0
  42. data/lib/kruczie/version.rb +3 -0
  43. data/lib/kruczie.rb +3 -0
  44. data/lib/tasks/kruczie/import.rake +11 -0
  45. data/src/data/snapshot.json +1 -0
  46. metadata +126 -0
@@ -0,0 +1,86 @@
1
+ types:
2
+ - name: neum
3
+ fields:
4
+ - name: id
5
+ kind: integer
6
+ - name: title
7
+ kind: string
8
+ - name: note
9
+ kind: string
10
+ - name: kind
11
+ kind: string
12
+ - name: type
13
+ kind: string
14
+ - name: zf
15
+ kind: array string
16
+ - name: glyphing
17
+ kind: array string
18
+ - name: sampling
19
+ kind: array string
20
+ - name: notation
21
+ kind: array string
22
+ - name: tones
23
+ kind: array integer
24
+ - name: source_id
25
+ kind: integer
26
+ - name: source_title
27
+ kind: string
28
+ - name: bond_to_id
29
+ kind: integer
30
+ - name: root_id
31
+ kind: integer
32
+ - name: neum_tag_ac
33
+ fields:
34
+ - name: key
35
+ kind: string
36
+ - name: value
37
+ kind: string
38
+ resources:
39
+ - name: neum.search
40
+ controller: neumos
41
+ path: /api/v0/neumos.json
42
+ methods:
43
+ - name: get
44
+ action: search
45
+ policy: 'no'
46
+ kind: neum page
47
+ description: :kruczie.resources.neum.search.description
48
+ allowed_errors: [200, 400, 500]
49
+ args:
50
+ - name: q
51
+ kind: string
52
+ description: :kruczie.resources.neum.search.query
53
+ - name: tags
54
+ kind: array string
55
+ - name: exact
56
+ kind: boolean
57
+ - name: kind
58
+ kind: string
59
+ - name: tone
60
+ kind: natural
61
+ maximum: 8
62
+ - name: page
63
+ kind: natural
64
+ default: 1
65
+ - name: per
66
+ kind: natural
67
+ default: 20
68
+ maximum: 100
69
+ - name: neum.tag.autocomplete
70
+ controller: neumos
71
+ path: /api/v0/neumos/tags/ac.json
72
+ methods:
73
+ - name: get
74
+ action: autocomplete
75
+ policy: 'no'
76
+ kind: neum_tag_ac page
77
+ description: :kruczie.resources.neum.tag.autocomplete.description
78
+ allowed_errors: [200, 400, 500]
79
+ args:
80
+ - name: q
81
+ kind: string
82
+ alias: query
83
+ - name: per
84
+ kind: natural
85
+ default: 30
86
+ maximum: 512
@@ -0,0 +1,60 @@
1
+ require "json"
2
+ require "rails/generators"
3
+
4
+ module Kruczie
5
+ module Generators
6
+ module Tiun
7
+ class Generator < Rails::Generators::Base
8
+ namespace "kruczie:tiun"
9
+ source_root File.expand_path("../templates", __dir__)
10
+
11
+ class_option :tiun, type: :boolean, default: true, desc: "Use Tiun routes and components when available"
12
+ class_option :path, type: :string, default: "/singing", desc: "Root-relative page path"
13
+ class_option :controller, type: :string, default: "neumos", desc: "Host page controller"
14
+ class_option :action, type: :string, default: "page", desc: "Host page action"
15
+ class_option :source_path, type: :string, default: "", desc: "Root-relative resource catalog path"
16
+ class_option :header, type: :string, desc: "Configured component for the host header"
17
+ class_option :footer, type: :string, desc: "Configured component for the host footer"
18
+
19
+ # Installs the catalog controller with either Tiun or ordinary Rails routes.
20
+ # @return [void]
21
+ def install
22
+ config = Rails.application.config
23
+ settings = config.respond_to?(:tiun) && config.tiun
24
+ use_tiun = options[:tiun] && settings && settings.enabled != false
25
+ validate_page_paths if use_tiun
26
+ copy_file "app/controllers/neumos_controller.rb"
27
+
28
+ if use_tiun
29
+ install_tiun(settings.config_path.presence || "app/tiun")
30
+ else
31
+ route 'get "/neumos.json", to: "neumos#search"'
32
+ route 'get "/neumos/tags/ac.json", to: "neumos#autocomplete"'
33
+ end
34
+ end
35
+
36
+ private
37
+
38
+ # Verifies that the configured page and source links are local paths.
39
+ # @return [void]
40
+ def validate_page_paths
41
+ local = %r{\A/(?!/)[^?#]*\z}
42
+ return if local.match?(options[:path]) && (options[:source_path].empty? || local.match?(options[:source_path]))
43
+
44
+ raise Thor::Error, "Page and source paths must start at the site root"
45
+ end
46
+
47
+ # Writes Tiun metadata and registers the HTML page with the host Rails router.
48
+ # @param directory [String] Application's Tiun configuration directory.
49
+ # @return [void]
50
+ def install_tiun(directory)
51
+ template "kruczie.yaml.erb", File.join(directory, "kruczie.yaml")
52
+ copy_file "kruczie_server.yaml", File.join(directory, "kruczie_server.yaml")
53
+ copy_file File.expand_path("../../../../config/locales/ru.yml", __dir__), "config/locales/kruczie.ru.yml"
54
+ destination = "#{options[:controller]}##{options[:action]}"
55
+ route "get #{options[:path].inspect}, to: #{destination.inspect}, format: false"
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,47 @@
1
+ require "active_support/concern"
2
+
3
+ module Kruczie
4
+ module Model
5
+ module Neum
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ self.table_name = "neumos"
10
+ self.store_full_sti_class = false
11
+
12
+ belongs_to :source, class_name: "::Resource", optional: true
13
+ belongs_to :bond_to, class_name: "::Neum", optional: true
14
+ belongs_to :root, class_name: "::Neum", optional: true
15
+
16
+ validates :kind, inclusion: { in: %w[kruk demestvik greek] }
17
+ validates :version, :key, :type, presence: true
18
+
19
+ before_validation :assign_root
20
+ after_create :assign_self_root
21
+ end
22
+
23
+ class_methods do
24
+ # Resolves a short STI discriminator inside the Neum hierarchy.
25
+ # @param type_name [String] Short STI discriminator stored in neumos.type.
26
+ # @return [Class] Registered Neum subclass.
27
+ def sti_class_for(type_name)
28
+ base_class.const_get(type_name, false)
29
+ end
30
+ end
31
+
32
+ private
33
+
34
+ # Inherits the root of a variant's parent before validation.
35
+ # @return [void]
36
+ def assign_root
37
+ self.root_id = bond_to ? bond_to.root_id : id
38
+ end
39
+
40
+ # Links a newly persisted root to itself, once its primary key exists.
41
+ # @return [void]
42
+ def assign_self_root
43
+ update_column(:root_id, id) unless bond_to
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,11 @@
1
+ module Kruczie
2
+ class Railtie < Rails::Railtie
3
+ generators do
4
+ require "generators/kruczie/generator"
5
+ end
6
+
7
+ rake_tasks do
8
+ load File.expand_path("../tasks/kruczie/import.rake", __dir__)
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,142 @@
1
+ require "json"
2
+
3
+ require_relative "text"
4
+
5
+ module Kruczie
6
+ module Services
7
+ class Import
8
+ SNAPSHOT = File.expand_path("../../../src/data/snapshot.json", __dir__)
9
+ KINDS = { "znamenny" => "kruk", "demestvenny" => "demestvik", "greek" => "greek" }.freeze
10
+ TYPES = { 1 => "Ditty", 2 => "Exultee", 3 => "Theta" }.freeze
11
+
12
+ # Initializes the importer in the host's locale context.
13
+ # @param context [Hash] Optional locale, colanguage and coalphabeth.
14
+ # @return [Import] Import service.
15
+ def initialize(context = {})
16
+ @text = Text.new(context)
17
+ end
18
+
19
+ # Imports sources, catalog rows and formula variants in one transaction.
20
+ # - An import of the same version updates existing rows.
21
+ # - An unrecognized source, tradition or formula type aborts the transaction.
22
+ # @param file [String] Snapshot path, defaulting to the bundled snapshot.
23
+ # @return [String] Version of the imported snapshot.
24
+ def call(file = SNAPSHOT)
25
+ snapshot = JSON.parse(File.read(file))
26
+ @version = snapshot.fetch("manifest").fetch("version")
27
+ @tags = {}
28
+ Neum.transaction do
29
+ Neum.connection.execute("SELECT pg_advisory_xact_lock(hashtext('kruczie.import'))")
30
+ @sources = snapshot.fetch("sources").to_h do |source|
31
+ [source.fetch("_id"), save_source(source)]
32
+ end
33
+ snapshot.fetch("catalogs").each { |catalog| save_catalog(catalog) }
34
+ snapshot.fetch("formulas").each { |formula| save_formula(formula) }
35
+ end
36
+ @version
37
+ end
38
+
39
+ private
40
+
41
+ # Reuses a resource by its typed snapshot ID and updates its bibliography.
42
+ # @param data [Hash] Source from the snapshot.
43
+ # @return [Resource] Saved resource.
44
+ def save_source(data)
45
+ id = data.fetch("_id")
46
+ resource = Resource::Volumen.where("props #> '{kruczie,source_id}' = CAST(? AS jsonb)", JSON.generate(id))
47
+ .first_or_initialize
48
+ props = resource.props || {}
49
+ resource.update!(props: props.merge("short_name" => data["shortname"], "author" => data["author"],
50
+ "kruczie" => (props["kruczie"] || {}).merge("source_id" => id)))
51
+ @text.write(resource, :title, data.fetch("name"))
52
+ @text.write(resource, :description, data["description"])
53
+ resource
54
+ end
55
+
56
+ # Saves empty group roots and the symbol variants they organize.
57
+ # @param catalog [Hash] Tradition and its symbol groups.
58
+ # @return [void]
59
+ def save_catalog(catalog)
60
+ tradition = catalog.fetch("tradition")
61
+ kind = KINDS.fetch(tradition)
62
+ catalog.fetch("groups").each do |group|
63
+ group_id = group.fetch("_id")
64
+ prefix = "#{tradition}:#{entity_key(group_id)}"
65
+ root = save_neum("Symbol", "group:#{prefix}", group, kind: kind, zf: [])
66
+ group.fetch("symbols").each_with_index do |symbol, index|
67
+ save_neum("Symbol", "#{prefix}:#{index}", symbol, kind: kind, bond_to: root,
68
+ zf: Array(symbol["zf"].presence), glyphing: Array(symbol["value"].presence),
69
+ notation: Array(symbol["notes"].presence), sonus_count: symbol["sounds"].presence&.then { |count| Integer(count) },
70
+ tag_ids: Array(symbol["opts"]).uniq.map { |label| tag_id(label) })
71
+ end
72
+ end
73
+ end
74
+
75
+ # Saves the expanded formula and, when present, its contracted form.
76
+ # @param formula [Hash] Formula from the snapshot.
77
+ # @return [void]
78
+ def save_formula(formula)
79
+ tradition = formula.fetch("tradition")
80
+ type = formula.fetch("type")
81
+ id = formula.fetch("sourceId")
82
+ source = @sources.fetch(id) { raise KeyError, "Unknown formula source #{id.inspect}" }
83
+ key = "#{tradition}:#{entity_key(id)}:#{type}:#{entity_key(formula.fetch('_id'))}"
84
+ tones = formula["tones"]
85
+ common = { kind: KINDS.fetch(tradition), source: source, tones: tones == (1..8).to_a ? nil : tones }
86
+ expanded = save_neum(TYPES.fetch(type), key, formula, **common, zf: formula.fetch("value"),
87
+ notation: formula.fetch("valueNotes"), sampling: formula.fetch("valueText"))
88
+ return if formula.fetch("view").empty?
89
+
90
+ save_neum("Secretlee", "secretlee:#{key}", formula, **common, zf: formula.fetch("view"),
91
+ sampling: formula.fetch("viewText"), bond_to: expanded)
92
+ end
93
+
94
+ # Writes one STI row and its localized text.
95
+ # @param type [String] Short name of the STI model.
96
+ # @param key [String] Stable key within the snapshot version.
97
+ # @param data [Hash] Original snapshot entry.
98
+ # @param attributes [Hash] Parsed catalog columns and relations.
99
+ # @return [Neum] Saved catalog row.
100
+ def save_neum(type, key, data, **attributes)
101
+ model = Neum.const_get(type, false)
102
+ row = model.find_or_initialize_by(version: @version, key: key)
103
+ row.update!(**attributes, original_no: data.fetch("_id").to_s)
104
+ @text.write(row, :title, data.fetch("name"))
105
+ @text.write(row, :note, data["pitch"].presence)
106
+ row
107
+ end
108
+
109
+ # Reuses a tag by its label in the import context.
110
+ # @param label [String] Snapshot option label.
111
+ # @return [Integer] Tag ID.
112
+ def tag_id(label)
113
+ @tags[label] ||= begin
114
+ tag = @text.matching(Tag.all, :title, label).first
115
+ if !tag && Tag.reflect_on_association(:appellations)
116
+ tag = @text.matching(Tag.all, :appellation, label).first
117
+ @text.write(tag, :title, label) if tag && @text.values([tag], :title)[tag.id].blank?
118
+ end
119
+ unless tag
120
+ tag = Tag.new
121
+ tag.title = label if tag.has_attribute?(:title)
122
+ @text.build_appellation(tag, label)
123
+ tag.save!
124
+ @text.write(tag, :title, label)
125
+ end
126
+ tag.id
127
+ end
128
+ end
129
+
130
+ # Preserves numeric and string IDs as distinct keys.
131
+ # @param value [String, Numeric] Snapshot identifier.
132
+ # @return [String] Type-qualified identifier.
133
+ def entity_key(value)
134
+ case value
135
+ when String then "string:#{value}"
136
+ when Numeric then "number:#{value}"
137
+ else raise TypeError, "Invalid catalog ID #{value.inspect}"
138
+ end
139
+ end
140
+ end
141
+ end
142
+ end
@@ -0,0 +1,24 @@
1
+ module Kruczie
2
+ module Services
3
+ module Schema
4
+ module_function
5
+
6
+ # Determines where the application's localized catalog texts belong.
7
+ # - An existing neumos table fixes the storage used by subsequent runs.
8
+ # - Host associations to an external table take precedence over the locale count.
9
+ # @param connection [ActiveRecord::ConnectionAdapters::AbstractAdapter] Host database.
10
+ # @return [Boolean] Whether titles, descriptions and notes need related rows.
11
+ def has_shared_text?(connection)
12
+ if connection.data_source_exists?("neumos")
13
+ return !connection.column_exists?("neumos", "title")
14
+ end
15
+
16
+ %w[Tag Resource].any? do |name|
17
+ model = name.safe_constantize
18
+ reflection = model&.reflect_on_association(:titles)
19
+ reflection && reflection.klass.table_name != model.table_name
20
+ end || I18n.available_locales.size > 1
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,83 @@
1
+ require_relative "text"
2
+
3
+ module Kruczie
4
+ module Services
5
+ class Search
6
+ # Reads catalog titles and notes in the server's locale context.
7
+ # @param context [Hash] Server locale, colanguage and coalphabeth.
8
+ # @return [Search] Search service.
9
+ def initialize(context = {})
10
+ @locale = context[:locale] || I18n.locale
11
+ @text = Text.new(context)
12
+ end
13
+
14
+ # Lists matching catalog entries.
15
+ # - An empty query shows a small selection of simple signs.
16
+ # - Missing tones in a row mean that it is valid for all tones.
17
+ # @param q [String, nil] Search term for titles and ZF.
18
+ # @param tags [Array<String>] Localized tag titles, all of which must match.
19
+ # @param exact [Boolean] Whether to exclude records with additional tags.
20
+ # @param kind [String, nil] Tradition discriminator.
21
+ # @param tone [Integer, nil] Liturgical tone.
22
+ # @param per [Integer] Maximum number of rows.
23
+ # @param offset [Integer] Number of matching rows to skip.
24
+ # @return [Array<Hash>] Catalog entries for serialization.
25
+ def neums(q: nil, tags: [], exact: false, kind: nil, tone: nil, per: 20, offset: 0)
26
+ records = Neum.where.not(zf: []).where(version: Neum.order(version: :desc).limit(1).select(:version))
27
+ records = filters(records, q, tags, exact, kind, tone)
28
+ if q.blank? && tags.empty? && kind.blank? && tone.nil?
29
+ records = records.where(type: "Symbol", sonus_count: 1)
30
+ simple_labels = Array(I18n.t("kruczie.resources.neum.search.simple_tags", locale: @locale, default: nil))
31
+ ids = simple_labels.flat_map { |label| @text.matching(Tag.all, :title, label).pluck(:id) }.uniq
32
+ records = records.where("tag_ids && ARRAY[?]::bigint[]", ids) if ids.any?
33
+ end
34
+ rows = records.order(:id).offset(offset).limit(per).to_a
35
+ titles = @text.values(rows, :title)
36
+ notes = @text.values(rows, :note)
37
+ sources = @text.values(Resource.where(id: rows.filter_map(&:source_id)).to_a, :title)
38
+ rows.map do |row|
39
+ row.attributes.symbolize_keys.slice(:id, :kind, :type, :zf, :glyphing, :sampling, :notation, :tones,
40
+ :source_id, :bond_to_id, :root_id).merge(title: titles[row.id], note: notes[row.id], source_title: sources[row.source_id])
41
+ end
42
+ end
43
+
44
+ # Finds tag labels available on the current catalog snapshot.
45
+ # @param q [String] Literal substring of the localized label.
46
+ # @param per [Integer] Maximum number of suggestions.
47
+ # @return [Array<Hash>] Tiun autocomplete options.
48
+ def tags(q = "", per: 30)
49
+ used = Neum.where(version: Neum.order(version: :desc).limit(1).select(:version))
50
+ tags = Tag.where(id: used.select("unnest(tag_ids)"))
51
+ tags = @text.matching(tags, :title, q, partial: true) if q.present?
52
+ labels = @text.values(tags.order(:id).limit(per).to_a, :title).values.compact.uniq.sort
53
+ labels.map { |label| { key: label, value: label } }
54
+ end
55
+
56
+ private
57
+
58
+ # Applies dictionary filters to the current snapshot.
59
+ # @param records [ActiveRecord::Relation] Visible catalog.
60
+ # @param q [String, nil] Literal ZF or title term.
61
+ # @param tags [Array<String>] Localized tag labels.
62
+ # @param exact [Boolean] Whether to exclude additional tags.
63
+ # @param kind [String, nil] Tradition discriminator.
64
+ # @param tone [Integer, nil] Requested tone.
65
+ # @return [ActiveRecord::Relation] Matching rows.
66
+ def filters(records, q, tags, exact, kind, tone)
67
+ records = records.where(kind: kind) if kind.present?
68
+ records = records.where("tones IS NULL OR ? = ANY(tones)", tone) if tone
69
+ if q.present?
70
+ pattern = "%#{ActiveRecord::Base.sanitize_sql_like(q)}%"
71
+ records = @text.matching(records, :title, q, partial: true)
72
+ .or(records.where("EXISTS (SELECT 1 FROM unnest(zf) AS sign WHERE sign ILIKE ?)", pattern))
73
+ end
74
+ groups = tags.uniq.map { |title| @text.matching(Tag.all, :title, title).pluck(:id) }
75
+ return records if groups.empty?
76
+ return records.none if groups.any?(&:empty?)
77
+
78
+ records = groups.reduce(records) { |scope, ids| scope.where("tag_ids && ARRAY[?]::bigint[]", ids) }
79
+ exact ? records.where("tag_ids <@ ARRAY[?]::bigint[]", groups.flatten.uniq) : records
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,112 @@
1
+ module Kruczie
2
+ module Services
3
+ class Text
4
+ # Selects localized records using the context and columns available in the host.
5
+ # @param context [Hash] Server context with locale, colanguage and coalphabeth.
6
+ # @return [Text] Text reader and writer for that context.
7
+ def initialize(context = {})
8
+ @locale = context[:locale] || I18n.locale
9
+ @language = context[:colanguage]
10
+ @alphabeth = context[:coalphabeth]
11
+ end
12
+
13
+ # Selects records whose localized field is equal to, or contains, the value.
14
+ # @param records [ActiveRecord::Relation] Records to filter.
15
+ # @param field [Symbol] Singular text field.
16
+ # @param value [String] Text to locate.
17
+ # @param partial [Boolean] Whether to use a case-insensitive substring search.
18
+ # @return [ActiveRecord::Relation] Filtered records.
19
+ def matching(records, field, value, partial: false)
20
+ return compare(records, records.klass.arel_table[field], value, partial) if records.klass.column_names.include?(field.to_s)
21
+
22
+ reflection = records.klass.reflect_on_association(field.to_s.pluralize)
23
+ related = reflection.klass
24
+ matches = compare(related.where(locale_columns(related)), related.arel_table[:text], value, partial)
25
+ matches = matches.where(describable_type: records.klass.base_class.polymorphic_name)
26
+ records.where(id: matches.select(:describable_id))
27
+ end
28
+
29
+ # Selects one text value per owner within the server's locale.
30
+ # @param records [Array<ActiveRecord::Base>] Records of one model.
31
+ # @param field [Symbol] Singular text field.
32
+ # @return [Hash<Integer, String>] Values indexed by owner ID.
33
+ def values(records, field)
34
+ return {} if records.empty?
35
+ model = records.first.class
36
+ if model.column_names.include?(field.to_s)
37
+ return records.to_h { |record| [record.id, record.public_send(field)] }
38
+ end
39
+
40
+ related = model.reflect_on_association(field.to_s.pluralize).klass
41
+ related.where(locale_columns(related).merge(describable_id: records.map(&:id),
42
+ describable_type: model.base_class.polymorphic_name))
43
+ .order(:id).pluck(:describable_id, :text).reverse.to_h
44
+ end
45
+
46
+ # Persists a text in its inline column or localized association.
47
+ # @param record [ActiveRecord::Base] Saved owner of the text.
48
+ # @param field [Symbol] Singular text field.
49
+ # @param value [String, nil] Text from the snapshot.
50
+ # @return [void]
51
+ def write(record, field, value)
52
+ if record.has_attribute?(field)
53
+ record.update!(field => value)
54
+ elsif value.present?
55
+ association = record.public_send(field.to_s.pluralize)
56
+ attributes = locale_columns(association.klass, value)
57
+ association.find_or_initialize_by(attributes).update!(text: value)
58
+ end
59
+ end
60
+
61
+ # Initializes a required translated appellation if the host model uses one.
62
+ # @param tag [ActiveRecord::Base] Unsaved tag.
63
+ # @param label [String] Snapshot label.
64
+ # @return [void]
65
+ def build_appellation(tag, label)
66
+ return unless tag.respond_to?(:appellations)
67
+
68
+ relation = tag.appellations
69
+ relation.build(**locale_columns(relation.klass, label), text: label)
70
+ end
71
+
72
+ private
73
+
74
+ # Builds equality or a literal substring condition on a text column.
75
+ # @param records [ActiveRecord::Relation] Records to filter.
76
+ # @param column [Arel::Attributes::Attribute] Text column.
77
+ # @param value [String] Search text.
78
+ # @param partial [Boolean] Whether to match a substring.
79
+ # @return [ActiveRecord::Relation] Filtered records.
80
+ def compare(records, column, value, partial)
81
+ return records.where(column.eq(value)) unless partial
82
+
83
+ escaped = ActiveRecord::Base.sanitize_sql_like(value)
84
+ records.where(column.matches("%#{escaped}%"))
85
+ end
86
+
87
+ # Maps context values to the text table's available locale columns.
88
+ # @param model [Class] Localized text model.
89
+ # @param value [String, nil] Source text for hosts that recognize scripts.
90
+ # @return [Hash] Locale attributes.
91
+ def locale_columns(model, value = nil)
92
+ columns = model.column_names
93
+ return { locale: @locale.to_s } if columns.include?("locale")
94
+
95
+ if model.reflect_on_association(:locale) && columns.include?("locale_id")
96
+ locale_model = model.reflect_on_association(:locale).klass
97
+ return { locale_id: locale_model.find_by!(code: @locale.to_s).id }
98
+ end
99
+
100
+ if defined?(::Languageble)
101
+ language, alphabeth = Languageble.la_for_string(value) if value.present?
102
+ else
103
+ language = @locale.to_s
104
+ end
105
+ {
106
+ language_code: @language || language,
107
+ alphabeth_code: @alphabeth || alphabeth,
108
+ }.compact.select { |key, _| columns.include?(key.to_s) }
109
+ end
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,3 @@
1
+ module Kruczie
2
+ VERSION = "1.1.0"
3
+ end
data/lib/kruczie.rb ADDED
@@ -0,0 +1,3 @@
1
+ require_relative "kruczie/version"
2
+ require_relative "kruczie/model/neum"
3
+ require_relative "kruczie/railtie" if defined?(Rails::Railtie)
@@ -0,0 +1,11 @@
1
+ require "kruczie/services/import"
2
+
3
+ namespace :kruczie do
4
+ desc "Import a Kruczie snapshot (FILE, LOCALE, LANGUAGE, ALPHABETH)"
5
+ task import: :environment do
6
+ context = { locale: ENV["LOCALE"], colanguage: ENV["LANGUAGE"], coalphabeth: ENV["ALPHABETH"] }
7
+ importer = Kruczie::Services::Import.new(context)
8
+ version = importer.call(ENV.fetch("FILE", Kruczie::Services::Import::SNAPSHOT))
9
+ puts "Imported Kruczie snapshot #{version}"
10
+ end
11
+ end