1. Koen Van der Auwera
  2. amanda

Commits

Koen Van der Auwera  committed be2395b

Add to_param

  • Participants
  • Parent commits b2a522e
  • Branches master

Comments (0)

Files changed (1)

File amanda/post.rb

View file
       raise Amanda::Error.new(data.inspect)
     end
 
+    def to_param
+      "/#{id.gsub(/(\d{4})(\d{2})(\d{2})(\d{4})/, "\\1/\\2/\\3/\\4")}/#{parameterize(title)}"
+    end
+
     def to_json
       {id: id, title: title, published: published, date: date, tags: tags, content: content}.to_json
     end
       end
     end
 
+    # http://stackoverflow.com/a/9420531
+    def non_ascii_encoding_options
+      @naeo ||= {
+        :invalid           => :replace,  # Replace invalid byte sequences
+        :undef             => :replace,  # Replace anything not defined in ASCII
+        :replace           => '',        # Use a blank for those replacements
+        :universal_newline => true       # Always break lines with \n
+      }
+    end
+
+    def remove_non_ascii(str)
+      str.encode Encoding.find('ASCII'), non_ascii_encoding_options
+    end
+
+    # https://github.com/rails/rails/blob/a4278766068ee89fc910e113ef93d82071757965/activesupport/lib/active_support/inflector/transliterate.rb#L81
+    def parameterize(str, sep="-")
+      parameterized_string = remove_non_ascii(str)
+      # Turn unwanted chars into the separator
+      parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
+      unless sep.nil? || sep.empty?
+        re_sep = Regexp.escape(sep)
+        # No more than one of the separator in a row.
+        parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
+        # Remove leading/trailing separator.
+        parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
+      end
+      parameterized_string.downcase
+    end
   end
 end