Class: ShowOffUtils
- Inherits:
-
Object
- Object
- ShowOffUtils
- Defined in:
- lib/showoff_utils.rb
Constant Summary collapse
- HEROKU_GEMS_FILE =
'.gems'
- HEROKU_BUNDLER_GEMS_FILE =
'Gemfile'
- HEROKU_CONFIG_FILE =
'config.ru'
- TYPES =
{ :default => lambda { |t,size,source,type| (t,"#{size} #{type}",source) }, 'title' => lambda { |t,size,dontcare| (t,size) }, 'bullets' => lambda { |t,size,dontcare| (t,"#{size} bullets incremental",["bullets","go","here"])}, 'smbullets' => lambda { |t,size,dontcare| (t,"#{size} smbullets incremental",["bullets","go","here","and","here"])}, 'code' => lambda { |t,size,src| (t,size,blank?(src) ? " @@@ Ruby\n code_here()" : src) }, 'commandline' => lambda { |t,size,dontcare| (t,"#{size} commandline"," $ command here\n output here")}, 'full-page' => lambda { |t,size,dontcare| (t,"#{size} full-page","![Image Description](image/ref.png)")}, }
- EXTENSIONS =
{ 'pl' => 'perl', 'rb' => 'ruby', 'erl' => 'erlang', # so not exhaustive, but probably good enough for now }
- REQUIRED_GEMS =
%w(redcarpet showoff heroku)
Class Method Summary collapse
-
.add_new_dir(dir) ⇒ Object
Adds the given directory to this presentation, appending it to the end of showoff.json as well.
-
.add_slide(options) ⇒ Object
Adds a new slide to a given dir, giving it a number such that it falls after all slides in that dir.
-
.adjust_size(lines, width) ⇒ Object
Determines a more optimal value for the size (e.g. small vs. smaller) based upon the size of the code being formatted.
- .blank?(string) ⇒ Boolean
-
.clone(url, branch = nil, path = nil) ⇒ Object
clone a repo url, then run a provided block.
- .create(dirname, create_samples, dirs = 'one') ⇒ Object
-
.create_file_if_needed(filename, force) ⇒ Object
Creates the given filename if it doesn’t exist or if force is true.
-
.create_gems_file(filename, password, force, formatter, header = nil) ⇒ Object
Creates the file that lists the gems for heroku.
- .default_style(dir = '.') ⇒ Object
- .default_style?(style, dir = '.') ⇒ Boolean
- .determine_filename(slide_dir, slide_name, number) ⇒ Object
- .determine_size_and_source(code) ⇒ Object
- .determine_title(title, slide_name, code) ⇒ Object
-
.find_next_number(slide_dir) ⇒ Object
Finds the next number in the given dir to name a slide as the last slide in the dir.
- .get_config_option(dir, option, default = nil) ⇒ Object
-
.github ⇒ Object
generate a static version of the site into the gh-pages branch.
-
.heroku(name, force = false, password = nil, use_dot_gems = false) ⇒ Object
name - String containing heroku name force - boolean if .gems/Gemfile and config.ru should be overwritten if they don’t exist password - String containing password to protect your heroku site; nil means no password protection use_dot_gems - boolean that, if true, indicates we should use the old, deprecated .gems file instead of Bundler.
- .lang(source_file) ⇒ Object
-
.make_slide(title, classes = "", content = nil) ⇒ Object
Makes a slide as a string.
-
.parse_options(option_string = "") ⇒ Object
Helper method to parse a comma separated options string and stores the result in a dictionrary.
- .pause_msg(dir = '.') ⇒ Object
- .presentation_config_file ⇒ Object
- .presentation_config_file=(filename) ⇒ Object
-
.read_code(source_file) ⇒ Object
Reads the code from the source file, returning the code, indented for markdown, as well as the number of lines and the width of the largest line.
- .showoff_markdown(dir = ".") ⇒ Object
- .showoff_pdf_options(dir = '.') ⇒ Object
- .showoff_renderer_options(dir = '.', default_options = MarkdownConfig::defaults(dir)) ⇒ Object
- .showoff_sections(dir, logger = nil) ⇒ Object
- .showoff_title(dir = '.') ⇒ Object
- .skeleton(config) ⇒ Object
-
.update(verbose = false) ⇒ Object
just update the repo in cwd.
- .validate(config) ⇒ Object
- .write_file(filename, slide) ⇒ Object
Class Method Details
.add_new_dir(dir) ⇒ Object
Adds the given directory to this presentation, appending it to the end of showoff.json as well
304 305 306 307 308 309 310 311 312 313 314 |
# File 'lib/showoff_utils.rb', line 304 def self.add_new_dir(dir) puts "Creating #{dir}..." Dir.mkdir dir showoff_json = JSON.parse(File.read(ShowOffUtils.presentation_config_file)) showoff_json["section"] = dir File.open(ShowOffUtils.presentation_config_file,'w') do |file| file.puts JSON.generate(showoff_json) end puts "#{ShowOffUtils.presentation_config_file} updated" end |
.add_slide(options) ⇒ Object
Adds a new slide to a given dir, giving it a number such that it falls after all slides in that dir. Options are:
- :dir
-
dir where we put the slide (if omitted, slide is output to $stdout)
-
- :name
-
name of the file, without the number prefix. (if omitted, a default is used)
-
- :title
-
title in the slide. If not specified the source file name is used. If THAT is not specified, uses the value of
:name
. If THAT is not specified, a suitable default is used
-
- :code
-
path to a source file to use as content (force :type to be ‘code’)
-
- :number
-
true if numbering should be done, false if not
-
- :type
-
the type of slide to create
-
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
# File 'lib/showoff_utils.rb', line 278 def self.() add_new_dir([:dir]) if [:dir] && !File.exist?([:dir]) [:type] = 'code' if [:code] title = determine_title([:title],[:name],[:code]) [:name] = 'new_slide' if ![:name] size,source = determine_size_and_source([:code]) type = [:type] || :default = TYPES[type].call(title,size,source) if [:name] filename = determine_filename([:dir],[:name],[:number]) write_file(filename,) else puts puts end end |
.adjust_size(lines, width) ⇒ Object
Determines a more optimal value for the size (e.g. small vs. smaller) based upon the size of the code being formatted.
377 378 379 380 381 382 383 384 385 386 387 |
# File 'lib/showoff_utils.rb', line 377 def self.adjust_size(lines,width) size = "" # These values determined empircally size = "small" if width > 50 size = "small" if lines > 15 size = "smaller" if width > 57 size = "smaller" if lines > 19 puts "WARNING: some lines are too long and might be truncated" if width > 65 puts "WARNING: your code is too long and may not fit on a slide" if lines > 23 size end |
.blank?(string) ⇒ Boolean
316 317 318 |
# File 'lib/showoff_utils.rb', line 316 def self.blank?(string) string.nil? || string.strip.length == 0 end |
.clone(url, branch = nil, path = nil) ⇒ Object
clone a repo url, then run a provided block
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
# File 'lib/showoff_utils.rb', line 214 def self.clone(url, branch=nil, path=nil) require 'tmpdir' Dir.mktmpdir do |dir| if branch system('git', 'clone', '-b', branch, '--single-branch', '--depth', '1', url, dir) else system('git', 'clone', '--depth', '1', url, dir) end dir = File.join(dir, path) if path Dir.chdir dir do yield if block_given? end end end |
.create(dirname, create_samples, dirs = 'one') ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/showoff_utils.rb', line 34 def self.create(dirname,create_samples,dirs='one') FileUtils.mkdir_p(dirname) Dir.chdir(dirname) do dirs = dirs.split(',') if create_samples dirs.each do |dir| # create section FileUtils.mkdir_p(dir) # create markdown file File.open("#{dir}/00_section.md", 'w+') do |f| f.puts ("Section Header", "center subsection") end File.open("#{dir}/01_slide.md", 'w+') do |f| f.puts ("My Presentation") end File.open("#{dir}/02_slide.md", 'w+') do |f| f.puts ("Bullet Points","bullets incremental",["first point","second point","third point"]) end end end # Create asset directories FileUtils.mkdir_p('_files/share') FileUtils.mkdir_p('_images') # create showoff.json File.open(ShowOffUtils.presentation_config_file, 'w+') do |f| sections = dirs.collect {|dir| {"section" => dir} } f.puts JSON.pretty_generate({ "name" => "My Preso", "sections" => sections }) end end end |
.create_file_if_needed(filename, force) ⇒ Object
Creates the given filename if it doesn’t exist or if force is true
filename - String name of the file to create force - if true, the file will always be created, if false, only create
if it's not there
block - takes a block that will be given the file handle to write
data into the file IF it's being created
Examples
create_file_if_needed("config.ru",false) do |file|
file.puts "require 'showoff'"
file.puts "run ShowOff.new"
end
Returns true if the file was created
560 561 562 563 564 565 566 567 568 569 570 |
# File 'lib/showoff_utils.rb', line 560 def self.create_file_if_needed(filename,force) if !File.exist?(filename) || force File.open(filename, 'w+') do |f| yield f end true else puts "#{filename} exists; not overwriting (see showoff help heroku)" false end end |
.create_gems_file(filename, password, force, formatter, header = nil) ⇒ Object
Creates the file that lists the gems for heroku
filename - String name of the file password - Boolean to indicate if we are setting a password force - Boolean to indicate if we should overwrite the existing file formatter - Proc/lambda that takes 1 argument, the gem name, and formats it for the file
This is so we can support both the old .gems and the new bundler Gemfile
header - Proc/lambda that creates any header information in the file
Returns a boolean indicating that we had to create the file or not.
536 537 538 539 540 541 542 |
# File 'lib/showoff_utils.rb', line 536 def self.create_gems_file(filename,password,force,formatter,header=nil) create_file_if_needed(filename,force) do |file| file.puts header.call unless header.nil? REQUIRED_GEMS.each { |gem| file.puts formatter.call(gem) } file.puts formatter.call("rack") if password end end |
.default_style(dir = '.') ⇒ Object
473 474 475 |
# File 'lib/showoff_utils.rb', line 473 def self.default_style(dir = '.') get_config_option(dir, 'style', '') end |
.default_style?(style, dir = '.') ⇒ Boolean
477 478 479 480 |
# File 'lib/showoff_utils.rb', line 477 def self.default_style?(style, dir = '.') default = default_style(dir) style.split('/').last.sub(/\.css$/, '') == default end |
.determine_filename(slide_dir, slide_name, number) ⇒ Object
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
# File 'lib/showoff_utils.rb', line 337 def self.determine_filename(,,number) raise "Slide name is required" unless if number next_num = find_next_number() = "#{next_num}_#{}" end if filename = "#{}/#{}.md" else filename = "#{}.md" end filename end |
.determine_size_and_source(code) ⇒ Object
320 321 322 323 324 325 326 327 328 |
# File 'lib/showoff_utils.rb', line 320 def self.determine_size_and_source(code) size = "" source = "" if code source,lines,width = read_code(code) size = adjust_size(lines,width) end [size,source] end |
.determine_title(title, slide_name, code) ⇒ Object
366 367 368 369 370 371 372 373 |
# File 'lib/showoff_utils.rb', line 366 def self.determine_title(title,,code) if blank?(title) title = title = File.basename(code) if code end title = "Title here" if blank?(title) title end |
.find_next_number(slide_dir) ⇒ Object
Finds the next number in the given dir to name a slide as the last slide in the dir.
356 357 358 359 360 361 362 363 364 |
# File 'lib/showoff_utils.rb', line 356 def self.find_next_number() ||= '.' max = Dir.glob("#{}/*.md").collect do |f| next unless f =~ /^#{}\/(\d+)/ $1.to_i end.compact.max || 0 sprintf("%02d", max+1) end |
.get_config_option(dir, option, default = nil) ⇒ Object
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 |
# File 'lib/showoff_utils.rb', line 496 def self.get_config_option(dir, option, default = nil) index = File.join(dir, ShowOffUtils.presentation_config_file) if File.exist?(index) data = JSON.parse(File.read(index)) if data.is_a?(Hash) if default.is_a?(Hash) default.merge(data[option] || {}) else data[option] || default end end else default end end |
.github ⇒ Object
generate a static version of the site into the gh-pages branch
200 201 202 203 204 205 206 207 208 209 210 211 |
# File 'lib/showoff_utils.rb', line 200 def self.github ShowOff.do_static(nil) FileUtils.touch 'static/.nojekyll' `git add -f static` sha = `git write-tree`.chomp tree_sha = `git rev-parse #{sha}:static`.chomp `git read-tree HEAD` # reset staging to last-commit ghp_sha = `git rev-parse gh-pages 2>/dev/null`.chomp extra = ghp_sha != 'gh-pages' ? "-p #{ghp_sha}" : '' commit_sha = `echo 'static presentation' | git commit-tree #{tree_sha} #{extra}`.chomp `git update-ref refs/heads/gh-pages #{commit_sha}` end |
.heroku(name, force = false, password = nil, use_dot_gems = false) ⇒ Object
name - String containing heroku name force - boolean if .gems/Gemfile and config.ru should be overwritten if they don’t exist password - String containing password to protect your heroku site; nil means no password protection use_dot_gems - boolean that, if true, indicates we should use the old, deprecated .gems file instead of Bundler
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
# File 'lib/showoff_utils.rb', line 165 def self.heroku(name, force = false, password = nil, use_dot_gems = false) modified_something = false if use_dot_gems modified_something = create_gems_file(HEROKU_GEMS_FILE, !password.nil?, force, lambda{ |gem| gem }) else modified_something = create_gems_file(HEROKU_BUNDLER_GEMS_FILE, !password.nil?, force, lambda{ |gem| "gem '#{gem}'" }, lambda{ "source :rubygems" }) end create_file_if_needed(HEROKU_CONFIG_FILE,force) do |file| modified_something = true file.puts 'require "showoff"' if password.nil? file.puts 'run ShowOff.new' else file.puts 'require "rack"' file.puts 'showoff_app = ShowOff.new' file.puts 'protected_showoff = Rack::Auth::Basic.new(showoff_app) do |username, password|' file.puts "\tpassword == '#{password}'" file.puts 'end' file.puts 'run protected_showoff' end end modified_something end |
.lang(source_file) ⇒ Object
519 520 521 522 |
# File 'lib/showoff_utils.rb', line 519 def self.lang(source_file) ext = File.extname(source_file).gsub(/^\./,'') EXTENSIONS[ext] || ext end |
.make_slide(title, classes = "", content = nil) ⇒ Object
Makes a slide as a string.
- title
-
title of the slide
- classes
-
any “classes” to include, such as ‘smaller’, ‘transition’, etc.
- content
-
slide content. Currently, if this is an array, it will make a bullet list. Otherwise the string value of this will be put in the slide as-is
242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/showoff_utils.rb', line 242 def self.(title,classes="",content=nil) = "<!SLIDE #{classes}>\n" << "# #{title}\n" << "\n" if content if content.kind_of? Array content.each { |x| << "* #{x.to_s}\n" } else << content.to_s end end end |
.parse_options(option_string = "") ⇒ Object
Helper method to parse a comma separated options string and stores the result in a dictionrary
Example:
"tpl=hpi,title=Over the rainbow"
will be stored as
{ "tpl" => "hpi", "title" => "Over the rainbow" }
13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/showoff_utils.rb', line 13 def self.(option_string="") result = {} if option_string option_string.split(",").each do |element| pair = element.split("=") result[pair[0]] = pair.size > 1 ? pair[1] : nil end end result end |
.pause_msg(dir = '.') ⇒ Object
469 470 471 |
# File 'lib/showoff_utils.rb', line 469 def self.pause_msg(dir = '.') get_config_option(dir, 'pause_msg', 'PAUSED') end |
.presentation_config_file ⇒ Object
26 27 28 |
# File 'lib/showoff_utils.rb', line 26 def self.presentation_config_file @presentation_config_file ||= 'showoff.json' end |
.presentation_config_file=(filename) ⇒ Object
30 31 32 |
# File 'lib/showoff_utils.rb', line 30 def self.presentation_config_file=(filename) @presentation_config_file = filename end |
.read_code(source_file) ⇒ Object
Reads the code from the source file, returning the code, indented for markdown, as well as the number of lines and the width of the largest line
392 393 394 395 396 397 398 399 400 401 402 403 404 |
# File 'lib/showoff_utils.rb', line 392 def self.read_code(source_file) code = " @@@ #{lang(source_file)}\n" lines = 0 width = 0 File.open(source_file) do |code_file| code_file.readlines.each do |line| code += " #{line}" lines += 1 width = line.length if line.length > width end end [code,lines,width] end |
.showoff_markdown(dir = ".") ⇒ Object
487 488 489 |
# File 'lib/showoff_utils.rb', line 487 def self.showoff_markdown(dir = ".") get_config_option(dir, "markdown", "redcarpet") end |
.showoff_pdf_options(dir = '.') ⇒ Object
482 483 484 485 |
# File 'lib/showoff_utils.rb', line 482 def self.(dir = '.') opts = get_config_option(dir, 'pdf_options', {:page_size => 'Letter', :orientation => 'Landscape'}) Hash[opts.map {|k, v| [k.to_sym, v]}] # keys must be symbols end |
.showoff_renderer_options(dir = '.', default_options = MarkdownConfig::defaults(dir)) ⇒ Object
491 492 493 494 |
# File 'lib/showoff_utils.rb', line 491 def self.(dir = '.', = MarkdownConfig::defaults(dir)) opts = get_config_option(dir, showoff_markdown(dir), ) Hash[opts.map {|k, v| [k.to_sym, v]}] if opts # keys must be symbols end |
.showoff_sections(dir, logger = nil) ⇒ Object
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 |
# File 'lib/showoff_utils.rb', line 406 def self.showoff_sections(dir, logger = nil) unless logger logger = Logger.new(STDOUT) logger.level = Logger::WARN end index = File.join(dir, ShowOffUtils.presentation_config_file) sections = ["."] # default boring showoff.json if File.exist?(index) begin data = JSON.parse(File.read(index)) logger.debug data if data.is_a?(Hash) sections = data['sections'] if data.include? 'sections' else sections = data end # each entry in sections can be: # - "filename.md" # - { "section": "filename.md" } # - { "section": [ "array.md, "of.md, "files.md"] } # - { "include": "sections.json" } sections = sections.map do |entry| next entry if entry.is_a? String next nil unless entry.is_a? Hash next entry['section'] if entry.include? 'section' section = nil if entry.include? 'include' file = entry['include'] path = File.dirname(file) data = JSON.parse(File.read(file)) if data.is_a? Array if path == '.' section = data else section = data.map do |source| "#{path}/#{source}" end end end end section end rescue => e logger.error "There was a problem with the presentation file #{index}" logger.error e. logger.debug e.backtrace sections = [] end end sections.flatten.compact end |
.showoff_title(dir = '.') ⇒ Object
465 466 467 |
# File 'lib/showoff_utils.rb', line 465 def self.showoff_title(dir = '.') get_config_option(dir, 'name', "Presentation") end |
.skeleton(config) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/showoff_utils.rb', line 69 def self.skeleton(config) if config FileUtils.cp(config, '.') ShowOffUtils.presentation_config_file = File.basename(config) end # Create asset directories FileUtils.mkdir_p('_files/share') FileUtils.mkdir_p('_images') self.showoff_sections('.').each do |filename| next if File.exist? filename puts "Creating: #{filename}" if filename.downcase.end_with? '.md' FileUtils.mkdir_p File.dirname(filename) File.open(filename, 'w+') do |f| if filename =~ /section/i # kind of looks like a section slide f.puts ("#{filename.sub(/\.md$/, '')}", "center subsection") else f.puts ("#{filename.sub(/\.md$/, '')}") end end else FileUtils.mkdir_p filename end end end |
.update(verbose = false) ⇒ Object
just update the repo in cwd
231 232 233 234 |
# File 'lib/showoff_utils.rb', line 231 def self.update(verbose=false) puts "Updating presentation repository..." if verbose system('git', 'pull') end |
.validate(config) ⇒ Object
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 |
# File 'lib/showoff_utils.rb', line 100 def self.validate(config) showoff = ShowOff.new!(:pres_file => config) validators = showoff.settings.showoff_config['validators'] || {} files = [] errors = [] # get a list of actual filenames self.showoff_sections('.').each do |section| if File.directory?(section) files << showoff.load_section_files(section) else files << section end end files.flatten! files.each do |filename| unless File.exist? filename errors << "Missing path: #{filename}" next end if filename.downcase.end_with? '.md' print '.' showoff.(filename.sub('.md',''), 'all', false).each_with_index do |block, index| lang, code, classes = block validator = validators[lang] if classes.include? 'no-validate' print '-' next elsif validator # write out a tempfile because many validators require files to work with Tempfile.open('showoff-validation') do |f| File.write(f.path, code) unless system("#{validator} #{f.path}", :out => File::NULL, :err => File::NULL) print 'F' errors << "Invalid #{lang} code on #{filename} [#{index}]" end end end end end end puts puts "Found #{errors.size} errors." unless errors.empty? errors.each { |err| puts " * #{err}" } exit! end end |
.write_file(filename, slide) ⇒ Object
330 331 332 333 334 335 |
# File 'lib/showoff_utils.rb', line 330 def self.write_file(filename,) File.open(filename,'w') do |file| file.puts end puts "Wrote #{filename}" end |