如何在Rails方法中调用方法

我正在努力在用户模型中调用方法。我有一个与此相似的长方法:

def find_content
  def find_x
  # call api
  end
  def find_y
  #call api
  end
  content = {"x": find_x,"y": find_y}
  return content
end

然后我尝试在模型中这样称呼它:

class User < ApplicationRecord
  def User.news
    # get result of find_content
    content = find_content
    # I also tried doing User.find_content when the function was inside the model
    ## the function then passes the content variable to my UserMailer which sends emails to my users with the content
  end

我尝试使用def self.find_content将自己的find_content放置在用户模型中,并且没有自己的部分。 我想知道在哪里放置可以在模型中使用的函数的最佳位置。

tooy12345 回答:如何在Rails方法中调用方法

如果我在哪里,我将创建一个Service类或一个lib类,然后将其命名。

不要在方法内部定义方法。试试这样的东西

class MyFancyService
  def find_content
    {"x": find_x,"y": find_y}
  end

  private
  def find_x
    #code
  end

  def find_y
    #code
  end
end

在模型内部

#remember to require your libs/services class in somewhere (maybe application.rb)
class User < ApplicationRecord
  def news
     MyFancyService.new.find_content    
  end
end

不要滥用Class方法(def self.bla),您应该有更多的实例方法。

,

出现此问题的原因是,查找内容实际上并不是用户所关心的问题,应该像Horacio所提到的那样将其分为一个单独的类,但是我认为User类不需要了解任何有关查找内容的知识。但是,可能需要一些用户信息才能正确找到内容。

我建议这样(假设您需要User对象中的某些东西来调用您的api)

class User      
  def user_stuff_needed_by_api
  end
end

class NewsAPI
    def initialize(user_stuff)
        # set stuff needed based on the user
    end
    def find_x
        # call api
        "x"
    end
    def find_y
        # call api
        "y"
    end
    def find_content
        {"x": find_x,"y": find_y}
    end
end

然后在控制器中拥有用户对象,因此从中获取所需的内容,创建api的实例并进行调用

user_stuff = @user.user_stuff_needed_by_api
news_api = NewsAPI.new(user_stuff)
content = news_api.find_content

如果您真的想在用户实例内调用api,而我认为您不应该这样做,则建议您通过设置器传递api实例,然后将find_content委托给该实例。像这样

class User
  def set_news_api(api)
    @news_api = api
  end
  def find_content
     @news_api.find_content
  end
end

最后,如果您真的要将所有这些内容都放在User类中,那么应该可以,但是不建议再次使用。

class User
  def self.find_x
    "xx"
    # call api
    end
  def self.find_y
    "yy"
    #call api
  end
  def find_content  
    {"x": self.class.find_x,"y": self.class.find_y}
  end
  def self.other_find_content
    {"other_x": find_x,"other_y": find_y}
  end
  def user_stuff_needed_by_api
  end
end

puts User.new.find_content
puts User.other_find_content
本文链接:https://www.f2er.com/3132826.html

大家都在问