Class: ActivePostgrest::Generators::ModelGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/generators/active_postgrest/model_generator.rb

Instance Method Summary collapse

Instance Method Details

#create_model_fileObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/generators/active_postgrest/model_generator.rb', line 31

def create_model_file
  path = "app/models/#{singular}.rb"

  if File.exist?(File.join(destination_root, path))
    say_status :exist, path, :blue
    say "        → add `include #{singular.camelize}Attributes` to #{path} if not present", :cyan
  else
    create_file(path, <<~RUBY)
      class #{singular.camelize} < ActivePostgrest::Base
        include #{singular.camelize}Attributes
      end
    RUBY
  end
end

#generate_attributes_concernObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/generators/active_postgrest/model_generator.rb', line 8

def generate_attributes_concern
  klass = singular.camelize
  defn  = ActivePostgrest::Base.connection.table_schema(table)
  props = defn['properties'] || {}

  attrs = props.filter_map do |col, info|
    type = ActivePostgrest::Base::POSTGRES_TYPE_CAST[info['format']]
    "    attribute :#{col}, :#{type}" if type
  end

  content = <<~RUBY
    # Auto-generated by `rails g active_postgrest:model #{name}`. Do not edit manually.
    module #{klass}Attributes
      extend ActiveSupport::Concern
      included do
    #{attrs.any? ? attrs.join("\n") : '    # no type casts needed'}
      end
    end
  RUBY

  create_file("app/models/concerns/#{singular}_attributes.rb", content, force: true)
end