Tag: Ruby

Rails + SEO = Fancy URLs

Today I've been thinking about "Seoing" my project and I have decided to tune it up a little. Would be nice to have urls like this:

2452254234-rails-seo-czyli-ladniejsze-adresy-url

Of course it was really easy in Rails to do this kind of stuff.

First of all, when you use find method in Rails - it casts your string into integer, so you don't need to strip SEO urls when using params[:id]:

Something.find(params[:id])

So, it is really easy to use it (nothing changes), but how to create such URL?

We take one of attributes (lets assume name), we remove all "non url" chars (spaces, any special chars, etc) and we do downcase on a gsub result. When we have our "seo part" we attach at the beginning of string object ID and that's all. I've developed simple method to convert string into url friendly:

  def to_url
    temp = self.downcase
    temp
    temp.gsub!(/[âäàãáäå�?ăąǎǟǡǻ�?ȃȧẵặ]/,'a')
    temp.gsub!(/[ëêéèẽēĕėẻȅȇẹȩęḙḛ�?ếễểḕḗệ�?]/,'e')
    temp.gsub!(/[�?iìíîĩīĭïỉ�?ịįȉȋḭɨḯ]/,'i')
    temp.gsub!(/[òóôõ�?�?ȯö�?őǒ�?�?ơǫ�?ɵøồốỗổȱȫȭ�?�?ṑṓ�?ớỡởợǭộǿ]/,'o')
    temp.gsub!(/[ùúûũūŭüủůűǔȕȗưụṳųṷṵṹṻǖǜǘǖǚừứữửự]/,'u')
    temp.gsub!(/[ỳýŷỹȳ�?ÿỷẙƴỵ]/,'y')
    temp.gsub!(/[ñǹń]/,'n')
    temp.gsub!(/[çć]/,'c')
    temp.gsub!(/[ß]/,'ss')
    temp.gsub!(/[œ]/,'oe')
    temp.gsub!(/[ij]/,'ij')
    temp.gsub!(/[�?ł]/,'l')
    temp.gsub!(/[ś]/,'s')
    temp.gsub!(/[źż]/,'z')
    temp.gsub!(/[^a-zA-Z 0-9]/, "")
    temp.gsub!(/\s/,'-')
    temp.gsub!(/\-+$/,'')
    temp.gsub!(/^\-+/,'')
    temp
  end

Performing:

"Rails + SEO = Fancy URLs".to_url

will give me:

"rails-seo-fancy-urls"

Now let's create method called url:

      # Create fancy seo friendly url
      def url
        "#{self.id}-#{self.name.to_url}"
      end

And finally we overwrite default Rails to_params method:

      def to_param
        self.url
      end

Now You can use nice, good-looking URLs without any additional changes in your application. Rails magic rulez :) If you want to use it in a various number of models, probably you will be interested in my Acts more SEO gem.

String to URL czyli jak zamienić nazwę lub tekst na link

Dzisiaj potrzebowałem napisać sobie metodę która nazwy działów zamieni na linki. Początkowo chciałem to zrealizować w modelu Menu gdzie po prostu wywoływałbym metodę to_url która zwracałaby mi adres w formie id-jakis-tam-link. Niestety wadą takiego rozwiązania jest fakt że wtedy linki mogłyby być generowane tylko z modelu Menu.

Aby tego uniknąć napisałem malutkie rozszerzenie do klasy String, które zamienia nam tekst na odpowiednik z samymi małymi literkami, usuwa nasze "ogonki", usuwa inne niechciane w URLach znaki oraz zamienia spacje na pauzy. Jest ona bardzo prosta i niezbyt elegancka ;) ale swoje robi. Sam proces zamiany znaków polskich na ich odpowiedniki "bezogonkowe" wzorowałem na kodzie Tomasha - ascii_tic. Jednak resztę miałem już napisaną zanim zacząłem szukać rozwiązania na usunięcie ogonków.

Poniżej zamieszczam cały kod rozwiązania:

# Dodatkowe metody klasy string

class String
  # Zwraca strina bez polskich literek, z małej litery, z usuniętymi innymi
  # znakami oraze z zamienioną spacją na pauze (-)
  def to_url
    temp = self.downcase
    temp
    temp.gsub!(/[âäàãáäå�?ăąǎǟǡǻ�?ȃȧẵặ]/,'a')
    temp.gsub!(/[ëêéèẽēĕėẻȅȇẹȩęḙḛ�?ếễểḕḗệ�?]/,'e')
    temp.gsub!(/[�?iìíîĩīĭïỉ�?ịįȉȋḭɨḯ]/,'i')
    temp.gsub!(/[òóôõ�?�?ȯö�?őǒ�?�?ơǫ�?ɵøồốỗổȱȫȭ�?�?ṑṓ�?ớỡởợǭộǿ]/,'o')
    temp.gsub!(/[ùúûũūŭüủůűǔȕȗưụṳųṷṵṹṻǖǜǘǖǚừứữửự]/,'u')
    temp.gsub!(/[ỳýŷỹȳ�?ÿỷẙƴỵ]/,'y')
    temp.gsub!(/[ñǹń]/,'n')
    temp.gsub!(/[çć]/,'c')
    temp.gsub!(/[ß]/,'ss')
    temp.gsub!(/[œ]/,'oe')
    temp.gsub!(/[ij]/,'ij')
    temp.gsub!(/[�?ł]/,'l')
    temp.gsub!(/[ś]/,'s')
    temp.gsub!(/[źż]/,'z')
    temp.gsub!(/[^a-zA-Z 0-9]/, "")
    temp.gsub!(/\s/,'-')
    temp.gsub!(/\-+$/,'')
    temp.gsub!(/^\-+/,'')
    temp
  end

  # to_url tylko wykonane na sobie
  def to_url!
    self.replace self.to_url
  end
end

Od teraz, mając jakikolwiek tekst, możemy na nim wywołac metodę to_url która zwróci nam jego "odpowiednik linkowy".

Copyright © 2025 Closer to Code

Theme by Anders NorenUp ↑