2016-05-31 3 views
1

Я использовал http://htmltohaml.com/, чтобы преобразовать мой ERB, и есть какая-то проблема.Ошибка после миграции из ERB в HAML

Рабочий Еврорадио перед обращенным

<h3><%= t("admin.labels.employee") %> <%= content_tag(:span, employee_counter) %></h3> 
<% 
    def create_validation_rules(field_rules) 
    Hash[field_rules.map do |rule| 
      next ["rule-#{rule[:name]}", rule[:value]] if rule[:value] 
      next ["msg-#{rule[:name]}", rule[:msg]] if rule[:msg] 
      end] if field_rules 
    end 
%> 
<div class="control-group form-controls"> 
    <%= f.label :first_name, t("labels.name") %> 
    <%= f.text_field :first_name, placeholder: t("labels.first_name"), class: 'js-employeeName', id: "merchant_employees_attributes_#{index}_first_name", name: "merchant[employees_attributes][#{index}][first_name]", autocomplete: "off", maxlength: 50, size: nil, data: create_validation_rules(validations[:first_name]) %> 
    <%= f.text_field :middle_name, placeholder: t("labels.middle_name"), id: "merchant_employees_attributes_#{index}_middle_name", name: "merchant[employees_attributes][#{index}][middle_name]", autocomplete: "off", maxlength: 100, size: nil %> 
    <%= f.text_field :last_name, placeholder: t("labels.last_name"), class: 'js-employeeName', id: "merchant_employees_attributes_#{index}_last_name", name: "merchant[employees_attributes][#{index}][last_name]", autocomplete: "off", maxlength: 50, size: nil, data: create_validation_rules(validations[:last_name]) %> 
</div> 
<div class="control-group"> 
    <%= f.label :email, t("labels.email_address") %> 
    <%= f.text_field :email, id: "merchant_employees_attributes_#{index}_email", name: "merchant[employees_attributes][#{index}][email]", autocomplete: "off", maxlength: 250, size: nil, data: create_validation_rules(validations[:email]) %> 
</div> 
<div class="control-group"> 
    <% if force_superuser_role %> 
     <%= f.hidden_field :superuser, value: "1" %> 
    <% else %> 
     <%= f.label :superuser, t("admin.labels.superuser") %> 
     <%= f.check_box :superuser, class: "superuser_checkbox", id: "merchant_employees_attributes_#{index}_superuser", name: "merchant[employees_attributes][#{index}][superuser]"%> 
    <% end %> 
</div> 

не работает HAML после обращенного:

Это моя ошибка: Показывается /Users/project/app/views/shared/_employee.html. Haml где строка # 9 поднятый:

%h3 
    = t("admin.labels.employee") 
    = content_tag(:span, employee_counter) 
- def create_validation_rules(field_rules) 
- Hash[field_rules.map do |rule| 
- next ["rule-#{rule[:name]}", rule[:value]] if rule[:value] 
- next ["msg-#{rule[:name]}", rule[:msg]] if rule[:msg] 
- end] if field_rules 
- end 
.control-group.form-controls 
    = f.label :first_name, t("labels.name") 
    = f.text_field :first_name, placeholder: t("labels.first_name"), class: 'js-employeeName', id: "merchant_employees_attributes_#{index}_first_name", name: "merchant[employees_attributes][#{index}][first_name]", autocomplete: "off", maxlength: 50, size: nil, data: create_validation_rules(validations[:first_name]) 
    = f.text_field :middle_name, placeholder: t("labels.middle_name"), id: "merchant_employees_attributes_#{index}_middle_name", name: "merchant[employees_attributes][#{index}][middle_name]", autocomplete: "off", maxlength: 100, size: nil 
    = f.text_field :last_name, placeholder: t("labels.last_name"), class: 'js-employeeName', id: "merchant_employees_attributes_#{index}_last_name", name: "merchant[employees_attributes][#{index}][last_name]", autocomplete: "off", maxlength: 50, size: nil, data: create_validation_rules(validations[:last_name]) 
.control-group 
    = f.label :email, t("labels.email_address") 
    = f.text_field :email, id: "merchant_employees_attributes_#{index}_email", name: "merchant[employees_attributes][#{index}][email]", autocomplete: "off", maxlength: 250, size: nil, data: create_validation_rules(validations[:email]) 
.control-group 
    - if force_superuser_role 
    = f.hidden_field :superuser, value: "1" 
    - else 
    = f.label :superuser, t("admin.labels.superuser") 
    = f.check_box :superuser, class: "superuser_checkbox", id: "merchant_employees_attributes_#{index}_superuser", name: "merchant[employees_attributes][#{index}][superuser]" 
+2

Почему вы определяете метод внутри представления ??? Вы просите о больших неприятностях. –

+1

Я мог бы предложить определить эту функцию в другом месте, например, в помощнике или вычислить это значение в контроллере. HAML и ERB не очень хорошо подходят для этой цели. –

+0

@ChaseGilliam В самом деле, HAML затрудняет определение функции во взгляде _былочные функции не должны определяться в представлениях. –

ответ

2

правильно способ справиться с этим является определение метода в качестве помощника в контроллере:

class MyController 
    helper_method :create_validation_rules 

private 
    def create_validation_rules(field_rules) 
    Hash[field_rules.map do |rule| 
     next ["rule-#{rule[:name]}", rule[:value]] if rule[:value] 
     next ["msg-#{rule[:name]}", rule[:msg]] if rule[:msg] 
    end] if field_rules 
    end 
end 

Это позволит вам позвонить create_validation_rules из представления, без необходимости определять способ там. См. In Rails, what exactly do helper and helper_method do?, чтобы точно понимать, что такое вспомогательный метод и как он работает.


Однако, если вы просто должны использовать встроенный метод в представлении кода, есть решение: вы можете просто устранить в встроенной функции последнего end, и правильно отступ тела функции и петля.

В этом случае сообщение об ошибке объяснили бы все:

You don't need to use "- end" in Haml. Un-indent to close a block

Обновление кода Haml, это работает:

%h3 
    = t("admin.labels.employee") 
    = content_tag(:span, employee_counter) 
- def create_validation_rules(field_rules) 
    - Hash[field_rules.map do |rule| 
    - next ["rule-#{rule[:name]}", rule[:value]] if rule[:value] 
    - next ["msg-#{rule[:name]}", rule[:msg]] if rule[:msg] 
    - end] if field_rules 
.control-group.form-controls 
    = f.label :first_name, t("labels.name") 
    = f.text_field :first_name, placeholder: t("labels.first_name"), class: 'js-employeeName', id: "merchant_employees_attributes_#{index}_first_name", name: "merchant[employees_attributes][#{index}][first_name]", autocomplete: "off", maxlength: 50, size: nil, data: create_validation_rules(validations[:first_name]) 
    = f.text_field :middle_name, placeholder: t("labels.middle_name"), id: "merchant_employees_attributes_#{index}_middle_name", name: "merchant[employees_attributes][#{index}][middle_name]", autocomplete: "off", maxlength: 100, size: nil 
    = f.text_field :last_name, placeholder: t("labels.last_name"), class: 'js-employeeName', id: "merchant_employees_attributes_#{index}_last_name", name: "merchant[employees_attributes][#{index}][last_name]", autocomplete: "off", maxlength: 50, size: nil, data: create_validation_rules(validations[:last_name]) 
.control-group 
    = f.label :email, t("labels.email_address") 
    = f.text_field :email, id: "merchant_employees_attributes_#{index}_email", name: "merchant[employees_attributes][#{index}][email]", autocomplete: "off", maxlength: 250, size: nil, data: create_validation_rules(validations[:email]) 
.control-group 
    - if force_superuser_role 
    = f.hidden_field :superuser, value: "1" 
    - else 
    = f.label :superuser, t("admin.labels.superuser") 
    = f.check_box :superuser, class: "superuser_checkbox", id: "merchant_employees_attributes_#{index}_superuser", name: "merchant[employees_attributes][#{index}][superuser]" 

В определение функции встроены в ERB код вида ненормально, http://htmltohaml.com не справлялся с этим, и просто извергал весь метод на выходе HAML. Хотя это явно неверно, просто исправить это.


Если вы быть хорошим гражданин чистого (и, как вы уже используете инструмент), вы будете сообщать этот вопрос к разработчику http://htmltohaml.com так, что он может объяснить этот класс поколения Haml вопрос.

+0

Спасибо! Он работает – christian

+0

У меня нет достаточной репутации для голосования :) В следующий раз. – christian

+0

Я смогу дать вам еще 5 позже, когда мои голоса пополняются.: D –

1

Лучший вариант для перемещения create_validation_rules в качестве помощника или по крайней мере сделать это в контроллере helper_method.

Чтобы сохранить его в Haml - вы должны использовать синтаксис Haml для блоков:

- def create_validation_rules(field_rules) 
    - if field_rules 
    - Hash.[] field_rules.map do |rule| 
     - if rule[:value] 
     - next ["rule-#{rule[:name]}", rule[:value]] 
     - if rule[:msg] 
     - next ["msg-#{rule[:name]}", rule[:msg]] 
Смежные вопросы