Class: DynamicActiveModel::TemplateClassFile
- Inherits:
-
Object
- Object
- DynamicActiveModel::TemplateClassFile
- 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
Instance Method Summary collapse
-
#create_template!(dir) ⇒ void
Creates a Ruby source file for the model.
-
#initialize(model) ⇒ TemplateClassFile
constructor
Initializes a new TemplateClassFile instance.
-
#to_s ⇒ String
Generates the Ruby source code for the model.
Constructor Details
#initialize(model) ⇒ TemplateClassFile
Initializes a new TemplateClassFile instance
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
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_s ⇒ String
Generates the Ruby source code for the model
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 |