2015-04-13 3 views
0

У меня есть приложение Rails, которое я пытаюсь реализовать редактор WYSIWYG (ртуть), чтобы пользователь мог обновлять статические страницы сайта.Могу ли я разобрать файл SLIM с помощью Nokogiri?

Пользователь будет сильным пользователем или каким-то человеком, которого я хочу обновить на своем сайте. Страница будет похожа на страницу index.slim.html. Содержимое для обновления - это статический контент (не сохраняется в БД).

Я использую Mercury.

Содержание обновления будет что-то вроде этого:

 hr 
     #header_content data-mercury='full' 
      p.lead Ratione, quasi, enim voluptates porro voluptas quaerat recusandae reprehenderit vitae aliquid earum ex quo assumenda doloremque ea dolores maxime error suscipit exercitationem. 

я следующие данные, представлены в контроллер Rails:

{"content"=>{"header_content"=>{"type"=>"full", "data"=>{}, "value"=>"<p class=\"lead\">\n     Ratione, quasi, enim voluptates porro voluptas quaerat recusandae reprehenderit vitae aliquid earum ex quo assumenda doloremque ea dolores maxime error suscipit exercitationem.\n    </p>", "snippets"=>{}}}, "_method"=>"PUT", "controller"=>"pages", "action"=>"mercury_update", "id"=>"index", "page"=>{"content"=>{"header_content"=>{"type"=>"full", "data"=>{}, "value"=>"<p class=\"lead\">\n     Ratione, quasi, enim voluptates porro voluptas quaerat recusandae reprehenderit vitae aliquid earum ex quo assumenda doloremque ea dolores maxime error suscipit exercitationem.\n    </p>", "snippets"=>{}}}}} 

Или печататься немного симпатичнее:

page to update: 
    "index" 
path to this page: 
    app/views/pages/index.html.slim 

Content: 
    Html ID: 
    header_content 
    html: 
    <p class="lead"> 
        Ratione, quasi, enim voluptates porro voluptas quaerat recusandae reprehenderit vitae aliquid earum ex quo assumenda doloremque ea dolores maxime error suscipit exercitationem. 
       </p> 

Итак, <div> с идентификатором header_content необходимо заменить его содержимое на HTML.

Как я могу найти Nokogiri, чтобы найти этот идентификатор, обновить содержимое (в Slim) и сохранить его? Нужно ли мне просто использовать Slim для любых страниц, которые должны иметь эту функцию?

+0

Я боюсь, ваш вопрос не совсем понятно, что вы имеете в виду под «обновить содержание (в тонкий) и сохранить его» ? Не хотите ли вы сохранить текстовую область HTML в своей базе данных и вывести ее на свою статическую страницу? – Liyali

+0

Будет ли это статичным? Я никогда не делал этого раньше, но я думал, что я хочу, чтобы пользователь обновил HTML (а не запись в БД). Это плохая идея? – Jeff

+0

Иными словами, пользователь будет редактировать вашу страницу на лету, не сохраняя ее в постоянном хранилище? – Liyali

ответ

0

Это не лучшее решение, но это то, что мне нужно:

def get_match(text, key) 
    return_hash = {} 
    replace_lines = [] 
    line_num = 0 
    indent = -1 
    matched_line = -1 
    last_line = text.count-1 
    text.each do |line| 
    line_num += 1 
    if line.include? key 
     indent = line.index(/[^ ]/) 
     return_hash[:matched_line] = {:line_number => line_num, :line_text => line, :leading_spaces => indent} 
     after_match = text[line_num..-1] 
     i = indent 
     after_line_num = line_num 
     after_match.each do |l| 
     after_line_num +=1 
     i = l.index(/[^ ]/) 
     if i <= indent 
      break 
     else 
      replace_lines.append({:line_number=> after_line_num, :line_text => l, :leading_spaces => i}) 
     end 

     end 
     return_hash[:replace_lines] = replace_lines 
     break 
    end 
    end 
    return_hash 
end 


def new_slim_page_content (old_page_content, new_content, key) 
    #run first function here 
    matches = get_match(old_page_content, key) 

    #create two temp files... convert html 2 slim 
    input_file = Tempfile.new('input') 
    input_file.write(new_content) 
    input_file.close 
    output_file = Tempfile.new('output') 
    output_file.close 

    # Can I do this without using system call? 
    `html2slim "#{input_file.path}" "#{output_file.path}"` 

    #put output_file contents in variable and delete temp files 
    output_file.open 
    output = output_file.read 
    input_file.unlink 
    output_file.unlink 

    #delete old lines 
    matched_line = matches[:matched_line][:line_number] - 1 #returns line number, want index 
    replace_lines = matches[:replace_lines] 
    replace_lines.each do |line| 
     old_page_content.delete_at(matched_line + 1) #the next index 
    end 

    #create new lines 
    output = output.split("\n") 
    initial_offset = (" " * (matches[:matched_line][:leading_spaces] +2)) 
    output.map! { |line| initial_offset + line + "\n"} 
    old_page_content.insert(matched_line + 1, output).flatten! 
    old_page_content = old_page_content.join 
end 


text = [] 
path_to_page = 'C:/dev/best_in_show/app/views/pages/index.html.slim' 

File.open(path_to_page, 'r') do |f| 
    f.each_line do |line| 
     text.append(line) 
    end 
end 

new_text = "<p class=\"lead\">test</p>" 
key = "#header_content" 
new_page = new_slim_page_content(text, new_text, key) 
File.open(path_to_page, 'w') do |f| 
    f.write(new_page) 
end 
Смежные вопросы