Class: DynamicActiveModel::TemplateClassFile

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamic-active-model/template_class_file.rb

Overview

The TemplateClassFile class generates Ruby source files for ActiveRecord models. It creates properly formatted class definitions that include:

  • Table name configuration

  • Has many relationships

  • Belongs to relationships

  • Has one relationships

  • Has and belongs to many relationships

  • Custom association options

Examples:

Basic Usage

model = DB::User
template = DynamicActiveModel::TemplateClassFile.new(model)
template.create_template!('app/models')

Generate Source String

model = DB::User
template = DynamicActiveModel::TemplateClassFile.new(model)
source = template.to_s

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ TemplateClassFile

Initializes a new TemplateClassFile instance

Parameters:

  • model (Class)

    The ActiveRecord model to generate a template for



25
26
27
# File 'lib/dynamic-active-model/template_class_file.rb', line 25

def initialize(model)
  @model = model
end

Instance Method Details

#create_template!(dir) ⇒ void

This method returns an undefined value.

Creates a Ruby source file for the model

Parameters:

  • dir (String)

    Directory to create the file in



32
33
34
35
# File 'lib/dynamic-active-model/template_class_file.rb', line 32

def create_template!(dir)
  file = dir + '/' + @model.name.underscore + '.rb'
  File.open(file, 'wb') { |f| f.write(to_s) }
end

#to_sString

Generates the Ruby source code for the model

Returns:

  • (String)

    The complete model class definition



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/dynamic-active-model/template_class_file.rb', line 39

def to_s
  str = "class #{@model.name} < ActiveRecord::Base\n".dup
  str << "  self.table_name = #{@model.table_name.to_sym.inspect}\n" unless @model.name.underscore.pluralize == @model.table_name
  all_has_many_relationships.each do |assoc|
    append_association!(str, assoc)
  end
  all_belongs_to_relationships.each do |assoc|
    append_association!(str, assoc)
  end
  all_has_one_relationships.each do |assoc|
    append_association!(str, assoc)
  end
  all_has_and_belongs_to_many_relationships.each do |assoc|
    append_association!(str, assoc)
  end
  str << "end\n"
  str
end