Class: MegaScaffold::CodeGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/mega_scaffold/code_generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ CodeGenerator

Returns a new instance of CodeGenerator.



5
6
7
# File 'lib/mega_scaffold/code_generator.rb', line 5

def initialize(options)
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/mega_scaffold/code_generator.rb', line 3

def options
  @options
end

Instance Method Details

#generateObject



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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/mega_scaffold/code_generator.rb', line 9

def generate
  strs = []
  options[:namespaces].each_with_index do |e, index|
    strs << "#{' ' * index}module #{index == 0 ? '::' + e : e}"
  end

  strs << %Q{
    class #{'::' if options[:namespaces].empty?}#{options[:model].to_s.pluralize}Controller < ::ApplicationController
      include MegaScaffold::Controller
      include Helpers

      #{"include " + options[:concerns].join(", ") if options[:concerns].any?} 

      helper :all

      def parent
        mega_scaffold.parent.call(self) if mega_scaffold.parent.is_a?(Proc)
      end

      def collection
        mega_scaffold.collection.call(self)
      end

      def resource
        collection.find(params[:id])
      end

      def find_parent
        @parent = parent
      end

      private
      def mega_scaffold
        @mega_scaffold ||= OpenStruct.new({
          scope: #{options[:scope][:as].to_s.to_json},
          model: #{options[:model]},
          pk: :#{options[:model].primary_key},
          fields: self.class.fields_config,
          columns: self.class.columns_config,
          form: self.class.form_config,
          show: self.class.show_config,
          collection: self.class.collection_config,
          parent: self.class.parent_config,
        })
      end

      def detect_layout
        "#{options[:layout].presence || 'application'}"
      end
    end
  }

  options[:namespaces].each_with_index do |e, index|
    strs << "#{' ' * (options[:namespaces].size - index - 1)}end"
  end

  klass_name = "#{options[:namespaces].any? ? options[:namespaces].join("::") + "::" : '::'}#{options[:model].to_s.pluralize}Controller"
  strs << klass_name

  # delete old constant
  # because it has conficts with same which was previosly initialized
  # happend after changing routes.rb in dev mode
  object_space = options[:namespaces].join("::").constantize rescue Object
  object_space.send(:remove_const, :"#{options[:model].to_s.pluralize}Controller") rescue '='

  strs.join("\n")
end