ruby 为什么我的自定义slug方法跳过它的代码?

utugiqy6  于 2023-03-01  发布在  Ruby
关注(0)|答案(2)|浏览(108)

我正在尝试执行以下操作来更改URL:
1.从我的网址解析"an-"的示例
1.删除前缀"的-"从我的网址如果存在。

class BlogPost < ApplicationRecord
  extend FriendlyId
  friendly_id :custom_slug, use: :history

  ...

  def custom_slug
    a = "#{title.to_s}"

    # goal is to remove the following words from url: an
    # the word being removed goes after "/\b and before \b/"
    # "#{title}".gsub! "/\ban\b/", ""
    a.gsub! "/\ban-\b/", ""

    # this should remove "the-" from the beginning of a slug if it's there
    if a.start_with?("the-")
      a.slice! "the-"
    end

    return a
  end

end

我尝试更改的标题是**"帖子的示例"**
friendly_id转换为:/the-example-of-an-the-post
我想要:/example-of-the-post
但是我的代码没有被执行,只是返回了原始的字符串,我知道我的代码的.slice!部分应该可以工作,但是我不知道我的代码在这个应用程序中是否正确或有效。

    • 更新**

根据@Schwern的建议,我得出了一些其他的结论来解决我的问题:
a = "#{title.to_s}"a = "#{title.to_s.downcase}"
用更简单的解决方案替换了有故障的REGEX:

if a.include?(" an ")
  a.gsub! " an ", " "
end

直接从Schwern,我的目标是:slug中的某些内容,而不是:title,因此它必须更改为:

if a.start_with?("the ")
  a.slice! "the "
end
fiei3ece

fiei3ece1#

您正在匹配帖子的标题。假设帖子的标题不是the-example-of-an-the-post,这是它转换为URL后的显示方式。标题可能是The example of an the post

jgwigjjp

jgwigjjp2#

一些提示

# a = "#{title.to_s.downcase}"
# No need for interpolation inside "#{}".
# If the title always returns a string, you don't need to_s.
# Add to_s only if there is a possibility of returning nil.
# It is also good to better name the variable
new_slug = title.downcase

new_slug.gsub!(" an ", " ") if new_slug.include?(" an ")
new_slug.slice!("the ") if new_slug.start_with?("the ")

# Don't need the return statement on the last line
new_slug

相关问题