Class: Card::Content

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/card/content.rb

Constant Summary collapse

ALLOWED_TAGS =
{}
ATTR_VALUE_RE =
[ /(?<=^')[^']+(?=')/, /(?<=^")[^"]+(?=")/, /\S+/ ]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content, format_or_card, opts = {}) ⇒ Content

Returns a new instance of Content.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/card/content.rb', line 10

def initialize content, format_or_card, opts={}
  @format =
    if Card===format_or_card
      Format.new format_or_card, :format=>nil
    else
      format_or_card
    end
  @opts = opts || {}

  unless Array === content
    content = parse_content content
  end
  super content
end

Instance Attribute Details

#chunksObject (readonly)

Returns the value of attribute chunks.



8
9
10
# File 'lib/card/content.rb', line 8

def chunks
  @chunks
end

#formatObject (readonly)

Returns the value of attribute format.



8
9
10
# File 'lib/card/content.rb', line 8

def format
  @format
end

#optsObject (readonly)

Returns the value of attribute opts.



8
9
10
# File 'lib/card/content.rb', line 8

def opts
  @opts
end

#revisionObject (readonly)

Returns the value of attribute revision.



8
9
10
# File 'lib/card/content.rb', line 8

def revision
  @revision
end

Class Method Details

.clean!(string, tags = ALLOWED_TAGS) ⇒ Object

this has been hacked for card to allow classes if the class begins with “w-”



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/card/content.rb', line 153

def clean!( string, tags = ALLOWED_TAGS )
  string.gsub( /<(\/*)(\w+)([^>]*)>/ ) do
    raw = $~
    tag = raw[2].downcase
    if attrs = tags[tag]
      "<#{raw[1]}#{
        attrs.inject([tag]) do |pcs, attr|
          q='"'
          rest_value=nil
          if raw[3] =~ /\b#{attr}\s*=\s*(?=(.))/i
            rest_value = $'
            idx = %w{' "}.index($1) and q = $1
            re = ATTR_VALUE_RE[ idx || 2 ]
            if match = rest_value.match(re)
              rest_value = match[0]
              if attr == 'class'
                rest_value = rest_value.split(/\s+/).find_all {|s| s=~/^w-/i}*' '
              end
            end
          end
          pcs << "#{attr}=#{q}#{rest_value}#{q}" unless rest_value.blank?
          pcs
        end * ' '
      }>"
    else
      " "
    end
  end.gsub(/<\!--.*?-->/, '')
end

.truncatewords_with_closing_tags(input, words = 25, truncate_string = "...") ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/card/content.rb', line 189

def truncatewords_with_closing_tags(input, words = 25, truncate_string = "...")
  if input.nil? then return end
  wordlist = input.to_s.split
  l = words.to_i - 1
  l = 0 if l < 0
  wordstring = wordlist.length > l ? wordlist[0..l].join(" ") : input.to_s
  # nuke partial tags at end of snippet
  wordstring.gsub!(/(<[^\>]+)$/,'')

  tags = []

  # match tags with or without self closing (ie. <foo />)
  wordstring.scan(/\<([^\>\s\/]+)[^\>]*?\>/).each { |t| tags.unshift(t[0]) }
  # match tags with self closing and mark them as closed
  wordstring.scan(/\<([^\>\s\/]+)[^\>]*?\/\>/).each { |t| if !(x=tags.index(t[0])).nil? then tags.slice!(x) end }
  # match close tags
  wordstring.scan(/\<\/([^\>\s\/]+)[^\>]*?\>/).each { |t|  if !(x=tags.rindex(t[0])).nil? then tags.slice!(x) end  }

  tags.each {|t| wordstring += "</#{t}>" }

  wordstring +='<span class="closed-content-ellipses">...</span>' if wordlist.length > l
    #    wordstring += '...' if wordlist.length > l
  wordstring.gsub! /<[\/]?br[\s\/]*>/, ' ' ## Also a hack -- get rid of <br>'s -- they make line view ugly.
  wordstring.gsub! /<[\/]?p[^>]*>/, ' ' ## Also a hack -- get rid of <br>'s -- they make line view ugly.
  wordstring
end

Instance Method Details

#cardObject



25
26
27
# File 'lib/card/content.rb', line 25

def card
  format.card
end

#chunk_listObject



29
30
31
# File 'lib/card/content.rb', line 29

def chunk_list
  @opts[:chunk_list] || @format.chunk_list
end

#clean_with_space_last!(string, tags = ALLOWED_TAGS) ⇒ Object



184
185
186
# File 'lib/card/content.rb', line 184

def clean_with_space_last! string, tags = ALLOWED_TAGS
  clean_without_space_last!(string, tags).gsub(/(?:^|\b) ((?:&nbsp;)+)/, '\1 ')
end

#each_chunkObject



46
47
48
49
50
51
52
53
54
55
# File 'lib/card/content.rb', line 46

def each_chunk
  return enum_for(:each_chunk) unless block_given?
  case __getobj__
    when Hash;   each { |k,v| yield v if Chunk::Abstract===v }
    when Array;  each { |e|   yield e if Chunk::Abstract===e }
    when String; # strings are all parsed in self, so no chunks in a String
    else
      Rails.logger.warn "error self is unrecognized type #{self.class} #{self.__getobj__.class}"
  end
end

#find_chunks(chunk_type) ⇒ Object



57
58
59
# File 'lib/card/content.rb', line 57

def find_chunks chunk_type
  each_chunk.select { |chunk| chunk.kind_of?(chunk_type) }
end

#inspectObject



42
43
44
# File 'lib/card/content.rb', line 42

def inspect
  "<#{__getobj__.class}:#{card}:#{self}>"
end

#parse_content(content) ⇒ Object



66
67
68
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/card/content.rb', line 66

def parse_content content
  @chunks = []

  if String===content
    position = last_position = 0
    prefix_regexp = Chunk.get_prefix_regexp chunk_list
    interval_string = ''

    while prefix_match = content[position..-1].match( prefix_regexp )
      prefix = prefix_match[0]                                                 # prefix of matched chunk
      chunk_start = prefix_match.begin(0) + position                           # content index of beginning of chunk

      if prefix_match.begin(0) > 0                                             # if matched chunk is not beginning of test string
        interval_string += content[ position..chunk_start-1 ]                  # hold onto the non-chunk part of the string
      end

      chunk_class = Chunk.find_class_by_prefix prefix                          # get the chunk class from the prefix
      match, offset = chunk_class.full_match content[chunk_start..-1], prefix  # see whether the full chunk actually matches (as opposed to bogus prefix)
      context_ok = chunk_class.context_ok? content, chunk_start                # make sure there aren't contextual reasons for ignoring this chunk
      position = chunk_start                                                   # move scanning position up to beginning of chunk

      if match                                                                 # we have a chunk match
        position += ( match.end(0) - offset.to_i )                             # move scanning position up to end of chunk
        if context_ok                                                          #
          @chunks << interval_string if interval_string.size > 0                # add the nonchunk string to the chunk list
          @chunks << chunk_class.new( match, self )                             # add the chunk to the chunk list
          interval_string = ''                                                 # reset interval string for next go-round
          last_position = position                                             # note that the end of the chunk was the last place where a chunk was found (so far)
        end
      else
        position += 1                                                          # no match.  look at the next character
      end

      if !match || !context_ok
        interval_string += content[chunk_start..position-1]                    # moving beyond the alleged chunk.  append failed string to "nonchunk" string
      end
    end
  end

  if chunks.any?
    if last_position < content.size
      remainder = content[ last_position..-1]                                  # handle any leftover nonchunk string at the end of content
      @chunks << remainder
    end
    chunks
  else
    content
  end
end

#process_content_object(&block) ⇒ Object



61
62
63
64
# File 'lib/card/content.rb', line 61

def process_content_object &block
  each_chunk { |chunk| chunk.process_chunk &block }
  self
end

#to_sObject



33
34
35
36
37
38
39
40
# File 'lib/card/content.rb', line 33

def to_s
  case __getobj__
  when Array;    map(&:to_s)*''
  when String;   __getobj__
  when NilClass; '' #raise "Nil Card::Content"
  else           __getobj__.to_s
  end
end