Class: Shaf::Generator::Model

Inherits:
Base
  • Object
show all
Defined in:
lib/shaf/generator/model.rb

Instance Attribute Summary

Attributes inherited from Base

#args

Instance Method Summary collapse

Methods inherited from Base

identifier, inherited, #initialize, #read_template, #render, #template_dir, usage, #write_output

Constructor Details

This class inherits a constructor from Shaf::Generator::Base

Instance Method Details

#callObject



8
9
10
11
12
13
14
15
16
# File 'lib/shaf/generator/model.rb', line 8

def call
  if model_name.empty?
    raise "Please provide a model name when using the model generator!"
  end

  create_model
  create_migration
  create_serializer
end

#create_migrationObject



56
57
58
59
# File 'lib/shaf/generator/model.rb', line 56

def create_migration
  migration_args = %W(create table #{table_name}) + args[1..-1]
  Migration::Generator.new(*migration_args).call
end

#create_modelObject



34
35
36
37
# File 'lib/shaf/generator/model.rb', line 34

def create_model
  content = render(template, opts)
  write_output(target, content)
end

#create_serializerObject



61
62
63
64
65
# File 'lib/shaf/generator/model.rb', line 61

def create_serializer
  serializer_args = %W(serializer #{model_name})
  serializer_args += args[1..-1].map { |arg| arg.split(':').first }
  Generator::Factory.create(*serializer_args).call
end

#form_fieldsObject



39
40
41
42
43
44
45
46
# File 'lib/shaf/generator/model.rb', line 39

def form_fields
  args[1..-1].map do |f|
    (name, type, label) = f.split(':')
    type ||= "string"
    label_str = label ? %Q(, label: "#{label}") : ""
    format 'field :%s, type: "%s"%s' % [name, type, label_str]
  end
end

#model_nameObject



18
19
20
# File 'lib/shaf/generator/model.rb', line 18

def model_name
  args.first || ""
end

#optsObject



48
49
50
51
52
53
54
# File 'lib/shaf/generator/model.rb', line 48

def opts
  {
    model_name: model_name,
    class_name: model_name.capitalize,
    form_fields: form_fields
  }
end

#table_nameObject



22
23
24
# File 'lib/shaf/generator/model.rb', line 22

def table_name
  Utils::pluralize model_name
end

#targetObject



30
31
32
# File 'lib/shaf/generator/model.rb', line 30

def target
  "api/models/#{model_name}.rb"
end

#templateObject



26
27
28
# File 'lib/shaf/generator/model.rb', line 26

def template
  'api/model.rb'
end