Method: Journaltxt.build

Defined in:
lib/journaltxt.rb

.build(text, opts = {}) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/journaltxt.rb', line 94

def self.build( text, opts={} )
  puts ":: Opts :::"
  pp opts

  outpath   = opts[:outpath]  || DEFAULTS[:outpath]
  name      = opts[:name]     || DEFAULTS[:name]
  add_date  = opts.fetch( :date, DEFAULTS[:date] )  ## special case boolean flag migth be false


  items = Parser.parse( text  )

  items.each_with_index do |item,i|
    ## add page_title
    ##   todo/fix:  check if title exists? do NOT overwrite - why? why not?

    page_meta = item[0]
    page_date = page_meta['date']

    page_title = ''
    if name.downcase == 'journal'  ## note: special case (do NOT auto-add journal to title)
      ## dont't add "default/generic" journal to title
    else
      page_title << "#{name} - "
    end
    page_title << "Day #{i+1}"
    page_title << " - #{page_date.strftime('%a, %-d %b')}"   if add_date

    page_meta['title'] = page_title
  end


  items.each_with_index do |item,i|
     page_meta    = item[0]
     page_content = item[1]

     page_date    = page_meta['date']
     page_title   = page_meta['title']

     path = ''
     path << "#{outpath}/#{page_date}"
     path << "-#{name.downcase}.md"      ## note: journal gets auto-added to the name too

     ##
     ##  check if path exits?
     page_root = File.dirname( File.expand_path( path ) )
     unless File.directory?( page_root )
       puts "   make (missing) output dirs >#{page_root}...<"
       FileUtils.makedirs( page_root )
     end


     puts "Writing entry #{i+1}/#{items.size} >#{page_title}< to #{path}..."

     ### todo:
     ##   add a comment in the yaml meta data block e.g.
     ##   #  Journal.TXT entry 1/4 - auto-built on xxxx by journaltxt v1.2.3
     ##   or something

     comment = "Journal.TXT entry #{i+1}/#{items.size} - auto-built on #{Time.now} by journaltxt/#{Journaltxt.version}"

     yaml_text = YAML.dump( page_meta )
     ## todo: check better way to add an upfront comment?
     ##   for now just replace leading --- with leading --- with comment
     yaml_text = yaml_text.sub( /^---[ ]*$\n?/, "---\n# #{comment}\n" )

     File.open( path, 'w:utf-8' ) do |f|
       f.write yaml_text
       f.write "---\n\n"
       f.write page_content
     end
  end
end