Class: Prigner::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/prigner/model.rb

Overview

Model

This class implements several methods for load a model file of template.

Basically behaviour as parser based in a ERB file placed in models directory of a Template.

Example:

# model: jedi/knight
class <%=name.capitalize%>
<%for attribute in attributes%>
  attr_accessor :<%=attribute%>
<%end%>
  def initialize(<%=attributes.join(",")%>)
  <%for attribute in attributes%>
    @<%=attribute%> = <%attribute%>
  <%end%>
  end

  def to_s
  <%for attribute in attributes%>
    "\n<%=attribute.capitalize%>: #{<%=attribute%>}"
  <%end%>
  end
end

<%=name%> = <%=name.capitalize%>.new("Yoda", "Jedi Grand Master")
# end model

$> model = Pringer::Model.new "jedi/knight", {
     :name       => "knight",
     :attributes => [ :name, :position ]
   }
$> model.build!
$> model.contents
=> class Knight
=> 
=>   attr_accessor :name
=>   attr_accessor :position
=> 
=>   def initialize(name,position)
=>
=>     @name = name
=>     @position = position
=>
=>   end
=>
=>   def to_s
=>
=>     "\nName: #{name}"
=>     "\nPosition: #{position}"
=>
=>   end
=> end
=>
=> knight = Knight.new("Yoda", "Jedi Grand Master")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, binder = {}) ⇒ Model

Initializes a model passing all attributes by Hash.



74
75
76
77
# File 'lib/prigner/model.rb', line 74

def initialize(path, binder = {})
  @path   = Pathname.new(path)
  @binder = (binder.kind_of? Hash) ? binder.to_struct : binder
end

Instance Attribute Details

#binderObject

Value bindings.



68
69
70
# File 'lib/prigner/model.rb', line 68

def binder
  @binder
end

#contentsObject (readonly)

Parsed contents.



65
66
67
# File 'lib/prigner/model.rb', line 65

def contents
  @contents
end

#file_writtenObject (readonly)

Result file written



71
72
73
# File 'lib/prigner/model.rb', line 71

def file_written
  @file_written
end

#pathObject (readonly)

Model path file.



62
63
64
# File 'lib/prigner/model.rb', line 62

def path
  @path
end

Instance Method Details

#build!Object

Build model contents.



80
81
82
83
# File 'lib/prigner/model.rb', line 80

def build!
  require "erb"
  @contents = ::ERB.new(@path.read).result(binder.binding)
end

#write(file) ⇒ Object

Write contents into file.



86
87
88
89
90
91
92
93
94
# File 'lib/prigner/model.rb', line 86

def write(file)
  @file_written = file
  file = Pathname.new(file)
  file.dirname.mkpath
  file.open "w+" do |output|
    output << self.build!
  end
  self
end