EagerELK/ditty

View on GitHub
lib/ditty/templates/controller.rb.erb

Summary

Maintainability
Test Coverage
# frozen_string_literal: true

require 'ditty/controllers/component_controller'
require '<%= folder %>/models/<%= model_name.underscore %>'
require '<%= folder %>/policies/<%= policy_name.underscore %>'

module <%= namespace %>
  class <%= controller_name %> < Ditty::ComponentController
    set model_class: <%= model_name %>
    set view_folder: Ditty::<%= namespace %>.view_folder

    # Add text fields that are searchable here
    SEARCHABLE = %i[].freeze
    # Add field filter definitions here
    FILTERS = [
      <%- many_to_ones.each do |key| -%>
      { name: :<%= key[:table].to_s.singularize %>, field: :<%= key[:columns].first || 'id' %> },
      <%- end -%>
    ].freeze

    helpers do
      # filter_options helpers that return options for filter dropdowns
      <%- many_to_ones.each do |key| -%>

      def <%= key[:table].to_s.singularize %>_options
        policy_scope(<%= key[:table].to_s.classify %>).as_hash(:<%= key[:key] || 'id' %>, :<%= name_column(key[:table]) %>)
      end
<% end -%>
    end
    <%- if columns.include?(:guid) || columns.include?(:slug) -%>

    def read(id)
      if id =~ /\A\d+\z/
        dataset.with_pk(id)
      <%- if columns.include?(:guid) -%>
      elsif id =~ /\A[0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12}\z/
        dataset.first(guid: id)
      <%- end -%>
      <%- if columns.include?(:slug) -%>
      else
        dataset.first(slug: id)
      <%- end -%>
      end
    end
    <%- end -%>
    <%- if many_to_ones.count.positive? -%>

    before '/' do
      <%- many_to_ones.each do |key| -%>
      param(:<%= key[:table].to_s.singularize %>, Integer) unless params[:<%= key[:table].to_s.singularize %>].blank?
      <%- end -%>
    end

    before '*', provides: 'html' do
      <%- many_to_ones.each do |key| -%>
      if <%= key[:table].to_s.classify %>.count.zero?
        flash[:info] = 'Please add a <%= key[:table].to_s.classify %> first.'
        redirect "#{settings.map_path}/<%= key[:table] %>/new"
      end
      <%- end -%>
    end
    <%- end -%>
  end
end