Sha256: 8b6bfbf7b90d39f52800493789208e1b65b72e01d4c4abd27c4db297df52b483

Contents?: true

Size: 849 Bytes

Versions: 2

Compression:

Stored size: 849 Bytes

Contents

require 'generator'
require 'date'
require 'time'

# http://project.ioni.st/post/925#post-925
class String
  def coerce
    attempt = nil
    while coercions.next?
      attempt = coercions.next
      break if !attempt.nil?
    end
    %w(@coercions @generator).each { |i| remove_instance_variable i }
    attempt.nil? ? self : attempt
  end

  def strip_html
    gsub(/<(?:[^>'"]*|(['"]).*?\1)*>/,'')
  end
  
private
  def coercions
    @coercions ||= Generator.new do |@generator|
      try { self == 'true' }
      try { [self == 'false', false] }
      try { [Date.parse(self), Time.parse(self)] }
      try { Integer(self) }
      try { Float(self) }
    end
  end

  def try
    attempt, desired = yield
    if attempt
      @generator.yield(desired.nil? ? attempt : desired)
    end
  rescue ArgumentError
    @generator.yield nil
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mofo-0.2.1 lib/microformat/string.rb
mofo-0.2 lib/microformat/string.rb