轨道中的命名约定。为什么在应用文件夹中找不到我的服务文件?



我在app/services中创建了一个名为TitleParser的服务文件。。。自定义文件夹。该文件名为titleparser.rb

class TitleParser
  attr_reader :connection
  def initialize(orig_url)
    @connection = Faraday.new(orig_url)
  end
  def obtain_title
    response = parse(connection.get)
    require 'pry' ; binding.pry
  end
  private
  def parse(response)
    JSON.parse(response.body)
  end
end

在我的模型中,我在应用程序/模型中有一个名为Link的模型,它调用它。

class Link < ActiveRecord::Base
  before_create :shorten_url
  before_create :set_defaults
  def shorten_url
    self.short_url = "bit.ly-remix/" + SecureRandom.urlsafe_base64(6)
  end
  def set_defaults
    self.clicks = 0 if clicks.blank?
    self.title = TitleParser.new(orig_url).obtain_title
  end
end

我收到了一个未定义的Link::TitleParser好几个小时,直到我将服务中的文件重命名为title_parser.rb。这里发生了什么?这是什么传统规则?

这是您遇到的一个标准Rails命名约定问题。注意你是如何命名类的:

class TitleParser

使用该名称,Rails将需要一个名为title_parser.rb

的文件

最新更新