current_page.rb
2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
module Kanjai
class CurrentPage
attr_reader :domain, :lang, :url
PAGE_ID = 0
PARENT_PAGE_ID=1
PAGE_URL=2
PAGE_DATA_ID=3
def initialize(domain:, lang:, url:)
@domain = domain
@lang = lang
@url = url
end
def call
mas = url.split('/').reject { |c| c.empty? }
root_page = nil
page_datum = nil
params = {}
page_urls = prepare_data
p url
p page_urls
record = page_urls.select{|item| item[:url] == url }.first
if record
page_datum = Kanjai::PageDatum.find(record[:data_id])
else
collection = page_urls.select{|item| item[:url].to_s.include?(':param') }
collection.each do |item|
if page_datum.nil?
mas_url = url.split('/')
mas_item_url = item[:url].split('/')
if mas_url.count == mas_item_url.count
mas_item_url.each_with_index do |segment, index|
if segment == ':param'
mas_item_url[index] = mas_url[index]
params[:param] = mas_url[index]
end
end
if mas_url == mas_item_url
page_datum = Kanjai::PageDatum.find(item[:data_id])
end
end
end
end
end
if page_datum.nil? && url == '/'
record = scope.select{|item| item[PAGE_URL] == '/' }.first
if record
page_datum = Kanjai::PageDatum.find(record[PAGE_DATA_ID])
end
end
{page: page_datum, params: params}
end
private
def scope
@scope ||= domain.pages.joins("left join kanjai_page_data on kanjai_pages.id = kanjai_page_data.page_id and kanjai_page_data.lang='#{lang}'").pluck(:id, :parent_id, 'kanjai_page_data.url', "kanjai_page_data.id")
end
def prepare_data
[].tap do |n|
scope.each do |item|
url = ((item[PAGE_URL].to_s.first == '/' ? [] : generate_url(item[PARENT_PAGE_ID])) + [item[PAGE_URL]]).flatten.reject { |e| e.nil? || e&.empty? || e.to_s == '/' }.join('/')
url = '/' + url if url.to_s.present? && url.first != '/'
n << {
id: item[PAGE_ID],
data_id: item[PAGE_DATA_ID],
url: url
}
end
end
end
def generate_url(parent_id)
url = []
if parent_id
parent_item = scope.select{|item| item[PAGE_ID] == parent_id }.first
url = [parent_item[PAGE_URL]] + url
url = (parent_item[PAGE_URL].to_s.first == '/' ? [] : generate_url(parent_item[PARENT_PAGE_ID])) + url
end
return url
end
end
end