Class: TrailblazerScaffold::Contract::Generate
- Inherits:
-
Object
- Object
- TrailblazerScaffold::Contract::Generate
- Defined in:
- lib/trailblazer_scaffold/contract/generate.rb
Constant Summary collapse
- BLACKLIST_COLUMNS =
%w(id created_at updated_at)
- PROPERTY_TYPES =
%i(integer float boolean)
Instance Method Summary collapse
- #call(model) ⇒ Object
- #generate_class_text(model) ⇒ Object
- #get_properties(model) ⇒ Object
- #validate_presence(allow_null) ⇒ Object
- #validation(property) ⇒ Object
- #validation_type(type) ⇒ Object
Instance Method Details
#call(model) ⇒ Object
8 9 10 11 12 13 14 |
# File 'lib/trailblazer_scaffold/contract/generate.rb', line 8 def call(model) model_path = model.to_s.downcase.split('::').join('/') dir_path = Rails.root.join('app/concepts', model_path, 'contract') FileUtils.mkdir_p(dir_path) unless File.directory?(dir_path) file_name = 'base.rb' File.write((dir_path + file_name), generate_class_text(model)) end |
#generate_class_text(model) ⇒ Object
16 17 18 19 20 21 22 23 |
# File 'lib/trailblazer_scaffold/contract/generate.rb', line 16 def generate_class_text(model) klass_text = "class #{model}\n class Contract::Base < Reform::Form\n" properties = get_properties(model) properties.each do |property| klass_text += " property :#{property[:name]}#{validation(property)}\n" end klass_text += " end\nend\n" end |
#get_properties(model) ⇒ Object
25 26 27 28 29 30 |
# File 'lib/trailblazer_scaffold/contract/generate.rb', line 25 def get_properties(model) model.columns.map do |column| next if BLACKLIST_COLUMNS.include? column.name { name: column.name, allow_null: column.default || column.null, type: column.type } end.compact end |
#validate_presence(allow_null) ⇒ Object
51 52 53 54 |
# File 'lib/trailblazer_scaffold/contract/generate.rb', line 51 def validate_presence(allow_null) return if allow_null ' presence: true' end |
#validation(property) ⇒ Object
32 33 34 35 36 37 |
# File 'lib/trailblazer_scaffold/contract/generate.rb', line 32 def validation(property) presence_validation = validate_presence(property[:allow_null]) type_validation = validation_type(property[:type]) return unless presence_validation || type_validation ", validates: {#{[presence_validation, type_validation].compact.join(',')} }" end |
#validation_type(type) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/trailblazer_scaffold/contract/generate.rb', line 39 def validation_type(type) return unless PROPERTY_TYPES.include?(type) case type when :integer ' numericality: { only_integer: true }' when :float ' numericality: { only_float: true }' when :boolean ' inclusion: { in: [true, false] }' end end |