Sha256: 04b1a0e78e38ef608060da745d334e9f335537273d23866ab69ed1227a5695cb

Contents?: true

Size: 1.02 KB

Versions: 2

Compression:

Stored size: 1.02 KB

Contents

class AssociatedGenerator < Rails::Generators::NamedBase
  source_root File.expand_path("templates", __dir__)

  def generate_associated_object_files
    template "associated.rb",      "app/models/#{name.underscore}.rb"
    template "associated_test.rb", "test/models/#{name.underscore}_test.rb"
  end

  def connect_associated_object
    record_file = "#{destination_root}/app/models/#{record_path}.rb"

    raise "Record class '#{record_klass}' does not exist" unless File.exist?(record_file)

    inject_into_class record_file, record_klass do
      optimize_indentation "has_object :#{associated_object_path}", 2
    end
  end

  private

  # The `:name` argument can handle model names, but associated object class names aren't singularized.
  # So these record and associated_object methods prevent that.
  def record_path  = record_klass.downcase.underscore
  def record_klass = name.camelize.deconstantize

  def associated_object_path  = associated_object_class.underscore
  def associated_object_class = name.camelize.demodulize
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_record-associated_object-0.8.3 lib/generators/associated/associated_generator.rb
active_record-associated_object-0.8.2 lib/generators/associated/associated_generator.rb