From fdfc0fc6c91b46a3ff769687e1a456ef2b205417 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Fri, 4 Jul 2014 15:16:00 -0600 Subject: Add a `required` option to the model generator Syntax was chosen to follow the passing of multiple options to decimal/numeric types. Curly braces, and allowing any of `,`, `.`, or `-` to be used as a separator to avoid the need for shell quoting. (I'm intending to expand this to all columns, but that's another PR. The `required` option will cause 2 things to change. `required: true` will be added to the association. `null: false` will be added to the column in the migration. --- .../lib/rails/generators/generated_attribute.rb | 24 ++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) (limited to 'railties/lib/rails') diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index c5326d70d1..f16bd8e082 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -44,8 +44,11 @@ module Rails return $1, limit: $2.to_i when /decimal\{(\d+)[,.-](\d+)\}/ return :decimal, precision: $1.to_i, scale: $2.to_i - when /(references|belongs_to)\{polymorphic\}/ - return $1, polymorphic: true + when /(references|belongs_to)\{(.+)\}/ + type = $1 + provided_options = $2.split(/[,.-]/) + options = Hash[provided_options.map { |opt| [opt.to_sym, true] }] + return type, options else return type, {} end @@ -123,7 +126,11 @@ module Rails end def polymorphic? - self.attr_options.has_key?(:polymorphic) + self.attr_options[:polymorphic] + end + + def required? + self.attr_options[:required] end def has_index? @@ -139,12 +146,21 @@ module Rails end def inject_options - "".tap { |s| @attr_options.each { |k,v| s << ", #{k}: #{v.inspect}" } } + "".tap { |s| options_for_migration.each { |k,v| s << ", #{k}: #{v.inspect}" } } end def inject_index_options has_uniq_index? ? ", unique: true" : "" end + + def options_for_migration + @attr_options.dup.tap do |options| + if required? + options.delete(:required) + options[:null] = false + end + end + end end end end -- cgit v1.2.3