Class: TrkDatatables::Generators::TrkDatatablesGenerator

Inherits:
Rails::Generators::NamedBase
  • Object
show all
Defined in:
lib/generators/trk_datatables/trk_datatables_generator.rb

Instance Method Summary collapse

Instance Method Details

#createObject



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
# File 'lib/generators/trk_datatables/trk_datatables_generator.rb', line 9

def create
  begin
    class_name.constantize
    @trk_class_name = "#{class_name.pluralize}Datatable"
    @trk_file_name = "#{plural_name}_datatable"
  rescue NameError => e
    Rails.logger.info e.message
    @skip_model = true
    @trk_class_name = "#{class_name}Datatable"
    @trk_file_name = "#{singular_name}_datatable"
  end

  template "trk_datatable.rb", "app/datatables/#{@trk_file_name}.rb"

  say <<~TEXT
    ======================================================================
    You can use in your controller

    # app/controllers/#{plural_name}_controller.rb
    class #{class_name.pluralize}Controller < ApplicationController
      def index
        @datatable = #{@trk_class_name}.new view_context
      end

      def search
        render json: #{@trk_class_name}.new(view_context)
      end
    end

    In your views mkdir app/views/#{plural_name}
    # app/views/#{plural_name}/index.html.erb
    <h1>#{class_name.pluralize}</h1>
    <%= @datatable.render_html search_#{plural_name}_path(format: :json) %>

    And in routes

    # config/routes.rb
    Rails.application.routes.draw do
      resources :#{plural_name} do
        collection do
          post :search
        end
      end
    end
    ======================================================================
  TEXT
end