Module: HasMeta::Extensions::ClassMethods

Defined in:
lib/has_meta.rb

Instance Method Summary collapse

Instance Method Details

#has_meta(options = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/has_meta.rb', line 12

def has_meta(options = {})
  options.each_pair do |meth, fields|
    define_method("meta_#{meth}") {|*args|
      length = args.first if args.is_a? Array
      length ||= 255

      if fields.is_a? Proc
        str = fields.call(self)
      else
        field = [*fields].detect{|f| send(f).present?}
        return nil if field.nil?
        str = send(field)
      end

      str = str.to_s.strip
      str.gsub!(' ', ' ')
      str.gsub!(/<.*?>/, '')

      if meth.to_s == 'keywords'
        str = str.gsub(/[\s,]{2,}/, ',').
                  gsub(/\s+/, ' ').
                  gsub(/^,|,$/, '').
                  strip 
      end

      str = ::CGI::unescapeHTML(str)
      str = (str[0,length - 3] + '...') if str.size > length
      str
    }
  end
end