Skip to content

Commit

Permalink
Implement index, show action, use hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
CuddlyBunion341 committed Oct 22, 2024
1 parent 3a79ee8 commit 12f4e56
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
52 changes: 52 additions & 0 deletions app/controllers/moirai/translation_files_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
require 'cgi'
require 'digest'

module Moirai
class TranslationFilesController < ApplicationController
def index
i18n_file_paths = I18n.load_path
@file_paths = i18n_file_paths.select { |path| (path.start_with? Rails.root.to_s) && path.end_with?(".yml", ".yaml") }
@file_hashes = @file_paths.map { |path| [Digest::SHA256.hexdigest(path), path] }.to_h
end

def show
i18n_file_paths = I18n.load_path
@file_paths = i18n_file_paths.select { |path| (path.start_with? Rails.root.to_s) && path.end_with?(".yml", ".yaml") }
@file_hashes = @file_paths.map { |path| [Digest::SHA256.hexdigest(path), path] }.to_h
file_path = @file_hashes[params[:id]]
decoded_path = CGI.unescape(file_path)
@translations = parse_file(decoded_path)
render json: @translations
end

private

def parse_file(path)
yaml_content = YAML.load_file(path)
root_key = yaml_content.keys.first
flatten_hash(yaml_content[root_key])
end

def flatten_hash(hash, parent_key = "", result = {})
hash.each do |key, value|
new_key = parent_key.empty? ? key.to_s : "#{parent_key}.#{key}"
case value
when Hash
flatten_hash(value, new_key, result)
when Array
value.each_with_index do |item, index|
array_key = "#{new_key}.#{index}"
if item.is_a?(Hash)
flatten_hash(item, array_key, result)
else
result[array_key] = item
end
end
else
result[new_key] = value
end
end
result
end
end
end
4 changes: 4 additions & 0 deletions app/views/moirai/translation_files/index.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<% @file_paths.each do |file| %>
<% file_hash = Digest::SHA256.hexdigest(file) %>
<%= link_to File.basename(file), translation_file_path(file_hash) %>
<% end %>
2 changes: 2 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@

Moirai::Engine.routes.draw do
root to: "pages#index"

resources :translation_files, only: %i[index show]
end

0 comments on commit 12f4e56

Please sign in to comment.