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



27
28
29
# File 'lib/dynamic-active-model/template_class_file.rb', line 27

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, at dir//.rb

Parameters:

  • dir (String) —

    Directory to create the file in



34
35
36
37
38
39
# File 'lib/dynamic-active-model/template_class_file.rb', line 34

def create_template!(dir)
  file = "#{dir}/#{@model.name.underscore}.rb"
  # the namespace directory (e.g. db/ for DB::User) may not exist yet
  FileUtils.mkdir_p(File.dirname(file))
  File.binwrite(file, to_s)
end

#to_s ⇒ String

Generates the Ruby source code for the model

Returns:

  • (String) —

    The complete model class definition



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/dynamic-active-model/template_class_file.rb', line 43

def to_s
  str = "class #{@model.name} < ActiveRecord::Base\n"
  unless @model.name.underscore.pluralize == @model.table_name
    str << "  self.table_name = #{@model.table_name.to_sym.inspect}\n"
  end
  all_has_many_relationships.each do |assoc|
    append_association!(str, 'has_many', assoc, has_many_association_options(assoc))
  end
  all_has_many_through_relationships.each { |assoc| append_through_association!(str, assoc) }
  all_belongs_to_relationships.each do |assoc|
    append_association!(str, 'belongs_to', assoc, belongs_to_association_options(assoc))
  end
  all_has_one_relationships.each do |assoc|
    append_association!(str, 'has_one', assoc, has_one_association_options(assoc))
  end
  all_has_and_belongs_to_many_relationships.each do |assoc|
    append_association!(str, 'has_and_belongs_to_many', assoc,
                        has_and_belongs_to_many_association_options(assoc))
  end
  str << "end\n"
  str
end