Class: PlutoniumGenerators::ModelGeneratorBase::GeneratedAttribute

Inherits:
Rails::Generators::GeneratedAttribute
  • Object
show all
Defined in:
lib/generators/pu/lib/plutonium_generators/model_generator_base.rb

Overview

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.parse(model_name, column_definition) ⇒ Object



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
# File 'lib/generators/pu/lib/plutonium_generators/model_generator_base.rb', line 73

def parse(model_name, column_definition)
  name, type, index_type = column_definition.split(":")

  # if user provided "name:index" instead of "name:string:index"
  # type should be set blank so GeneratedAttribute's constructor
  # could set it to :string
  index_type, type = type, nil if valid_index_type?(type)

  type, attr_options = *parse_type_and_options(type)
  type = type.to_sym if type

  if dangerous_name?(name)
    raise "Could not generate field '#{name}', as it is already defined by Active Record."
  end

  if type && !valid_type?(type)
    raise "Could not generate field '#{name}' with unknown type '#{type}'."
  end

  if index_type && !valid_index_type?(index_type)
    raise "Could not generate field '#{name}' with unknown index '#{index_type}'."
  end

  if type && reference?(type)
    if Rails::Generators::GeneratedAttribute::UNIQ_INDEX_OPTIONS.include?(index_type)
      attr_options[:index] = {unique: true}
    end

    if name.include? "/"
      attr_options[:to_table] = name.underscore.tr("/", "_").pluralize.to_sym
      attr_options[:class_name] = name.classify
      name = name.underscore
      if (shared_namespace = find_shared_namespace(model_name, name, separator: "/"))
        name = name.sub("#{shared_namespace}/", "")
      end
      name = name.tr("/", "_")
    end
  end

  new(name, type, index_type, attr_options)
end

Instance Method Details

#attribute_nameObject



157
158
159
160
161
162
163
# File 'lib/generators/pu/lib/plutonium_generators/model_generator_base.rb', line 157

def attribute_name
  if cents?
    name.sub("_cents", "")
  else
    name
  end
end

#cents?Boolean

Returns:

  • (Boolean)


153
154
155
# File 'lib/generators/pu/lib/plutonium_generators/model_generator_base.rb', line 153

def cents?
  type == :integer && name.ends_with?("_cents")
end

#options_for_migrationObject



165
166
167
168
169
170
171
172
# File 'lib/generators/pu/lib/plutonium_generators/model_generator_base.rb', line 165

def options_for_migration
  super.tap do |options|
    if options[:to_table]
      options[:foreign_key] = {to_table: options.delete(:to_table)}
    end
    options.delete(:class_name)
  end
end

#required?Boolean

Returns:

  • (Boolean)


147
148
149
150
151
# File 'lib/generators/pu/lib/plutonium_generators/model_generator_base.rb', line 147

def required?
  return false if attr_options[:null] == true

  super
end