Как добавить поле во фрагмент в удобном мексиканском диване

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

По умолчанию фрагменты содержат только два поля: "Метка" и "Идентификатор". И, конечно же, "Контент". Я хотел бы также добавить строку 'Subject' в поля.

1 ответ

Решение

Простой трехшаговый процесс:

1:

rails g migration AddSubjectToComfyCmsSnippets subject:string

2:

rake db:migrate

3:

Создайте app/views/comfy/admin/cms/snippets/_form.html.haml со следующим содержанием:

- content_for :right_column do
  = render 'comfy/admin/cms/files/index'
= render :partial => 'comfy/admin/cms/partials/snippet_form_before', :object => form
= form.text_field :label, :data => {:slugify => @snippet.new_record?}
= form.text_field :identifier, :data => {:slug => true}
= form.text_field :subject
= form.text_area :content, :data => {'cms-rich-text' => true}
= render :partial => 'comfy/admin/cms/categories/form', :object => form
= render :partial => 'comfy/admin/cms/partials/snippet_form_after', :object => form
= form.form_group :class => 'form-actions' do
  = form.submit t(@snippet.new_record?? '.create' : '.update'), :class => 'btn btn-primary'
  = link_to t('.cancel'), comfy_admin_cms_site_snippets_path, :class => 'btn btn-link'

Теперь вы можете ссылаться на тему в вашем приложении следующим образом:

Subject: #{@snippet.subject}

Патч обезьяны, чтобы заставить работать светильники:

Создайте config/initializers/cms_monkey_patch.rb со следующим содержанием:

ComfortableMexicanSofa::Fixture::Snippet::Importer.class_eval do
    def import!
      Dir["#{self.path}*/"].each do |path|
        identifier = path.split('/').last
        snippet = self.site.snippets.find_or_initialize_by(:identifier => identifier)

        # setting attributes
        categories = []
        if File.exists?(attrs_path = File.join(path, 'attributes.yml'))
          if fresh_fixture?(snippet, attrs_path)
            attrs = get_attributes(attrs_path)

            snippet.label = attrs['label']
            snippet.subject = attrs['subject']
            categories    = attrs['categories']
          end
        end

        # setting content
        %w(html haml).each do |extension|
          if File.exists?(content_path = File.join(path, "content.#{extension}"))
            if fresh_fixture?(snippet, content_path)
              snippet.content = extension == "html" ? 
                ::File.open(content_path).read : 
                Haml::Engine.new(::File.open(content_path).read).render.rstrip
            end
          end
        end

        # saving
        if snippet.changed? || self.force_import
          if snippet.save
            save_categorizations!(snippet, categories)
            ComfortableMexicanSofa.logger.info("[FIXTURES] Imported Snippet \t #{snippet.identifier}")
          else
            ComfortableMexicanSofa.logger.warn("[FIXTURES] Failed to import Snippet \n#{snippet.errors.inspect}")
          end
        end

        self.fixture_ids << snippet.id
      end

      # cleaning up
      self.site.snippets.where('id NOT IN (?)', fixture_ids).each{ |s| s.destroy }
    end
  end
end

ComfortableMexicanSofa::Fixture::Snippet::Exporter.class_eval do
    def export!
      prepare_folder!(self.path)

      self.site.snippets.each do |snippet|
        snippet_path = File.join(self.path, snippet.identifier)
        FileUtils.mkdir_p(snippet_path)

        # writing attributes
        open(File.join(snippet_path, 'attributes.yml'), 'w') do |f|
          f.write({
            'label'       => snippet.label,
            'subject'       => snippet.subject,
            'categories'  => snippet.categories.map{|c| c.label}
          }.to_yaml)
        end

        # writing content
        open(File.join(snippet_path, 'content.html'), 'w') do |f|
          f.write(snippet.content)
        end

        ComfortableMexicanSofa.logger.info("[FIXTURES] Exported Snippet \t #{snippet.identifier}")
      end
    end
end
Другие вопросы по тегам