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, at dir/
/ .rb. -
#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
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/
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
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, (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, (assoc)) end all_has_one_relationships.each do |assoc| append_association!(str, 'has_one', assoc, (assoc)) end all_has_and_belongs_to_many_relationships.each do |assoc| append_association!(str, 'has_and_belongs_to_many', assoc, (assoc)) end str << "end\n" str end |