Sha256: 6602c3d44cd12a3facb1c49429af425b7aea93c62db706793e5bcaecd8ceda99

Contents?: true

Size: 849 Bytes

Versions: 3

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

3 entries across 3 versions & 1 rubygems

Version Path
mofo-0.1.2 lib/microformat/string.rb
mofo-0.1 lib/microformat/string.rb
mofo-0.1.1 lib/microformat/string.rb