Module: DeclareSchema::Support::Model

Included in:
ModelGenerator
Defined in:
lib/generators/declare_schema/support/model.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/generators/declare_schema/support/model.rb', line 42

def included(base)
  base.class_eval do
    include EvalTemplate

    argument :attributes, type: :array, default: [], banner: "field:type field:type"

    class << self
      def banner
        "rails generate declare_schema:model #{arguments.map(&:usage).join(' ')} [options]"
      end
    end

    class_option :timestamps, type: :boolean

    def generate_model
      invoke "active_record:model", [name], { migration: false }.merge(options)
    end

    def inject_declare_schema_code_into_model_file
      gsub_file(model_path, /  # attr_accessible :title, :body\n/m, "")
      inject_into_class(model_path, class_name) do
        declare_model_fields_and_associations
      end
    end

    private

    def declare_model_fields_and_associations
      buffer = ::DeclareSchema::Support::IndentedBuffer.new(indent: 2)
      buffer.newline!
      buffer << 'declare_schema do'
      buffer.indent! do
        field_attributes.each do |attribute|
          decl = "%-#{max_attribute_length}s" % attribute.type + ' ' +
            attribute.name.to_sym.inspect +
            case attribute.type.to_s
            when 'string'
              ', limit: 255'
            else
              ''
            end
          buffer << decl
        end
        if options[:timestamps]
          buffer.newline!
          buffer << 'timestamps'
        end
      end
      buffer << 'end'

      if bts.any?
        buffer.newline!
        bts.each do |bt|
          buffer << "belongs_to #{bt.to_sym.inspect}"
        end
      end
      if hms.any?
        buffer.newline
        hms.each do |hm|
          buffer << "has_many #{hm.to_sym.inspect}, dependent: :destroy"
        end
      end
      buffer.newline!

      buffer.to_string
    end

    protected

    def model_path
      @model_path ||= File.join("app", "models", "#{file_path}.rb")
    end

    def max_attribute_length
      attributes.map { |attribute| attribute.type.length }.max
    end

    def field_attributes
      attributes.reject { |a| a.name == "bt" || a.name == "hm" }
    end

    def accessible_attributes
      field_attributes.map(&:name) + bts.map { |bt| "#{bt}_id" } + bts + hms
    end

    def hms
      attributes.select { |a| a.name == "hm" }.map(&:type)
    end

    def bts
      attributes.select { |a| a.name == "bt" }.map(&:type)
    end
  end
end