Ruby Rails APi 来自 Controller 的调用逻辑过多。我在哪里以及如何使它更简单?

Ruby on Rails APi call from Controller with too much logic. Where and how can I make it simpler?

我被要求在 Rails 上从 Ruby 获取口袋妖怪 API。但我很挣扎,因为我在控制器中有太多逻辑,这是不推荐的。我在哪里以及如何拨打电话,这样我的控制器内的逻辑就更少了。我有这个:

def index
    pokemons = []
    response = HTTParty.get("https://pokeapi.co/api/v2/pokemon?limit=6&offset=1")
    response = JSON.parse(response.body)
    response.each do |k, value|
        if k == "results"
            value.each do |key, val|
            response = HTTParty.get(key["url"])
            response = JSON.parse(response.body)
            pokemons.push(response)
            end
        end
    end

        @poke_json = pokemons.map do |poke|
            Pokemon.new(img:poke['sprites']['other']['dream_world']["front_default"], name: poke['forms'][0]['name'], weight: poke['weight'], poke_type: poke['types'][0]['type']['name'], poke_ability: poke['abilities'][0]['ability']['name'], poke_id: poke['id'])
                                                    
        end
    render json: { pokemons: @poke_json }
  end ``` 

作为第一步,您可以将 API 客户端依赖代码单独提取到 class 中:

# in app/models/pokemon_api.rb
class PokemonApi
  def self.to_json
    pokemons = []

    response = HTTParty.get("https://pokeapi.co/api/v2/pokemon?limit=6&offset=1")
    response = JSON.parse(response.body)
    response.each do |k, value|
      if k == "results"
        value.each do |key, val|
          response = HTTParty.get(key["url"])
          response = JSON.parse(response.body)
          pokemons.push(response)
        end
      end
    end

    pokemons.map do |poke|
      Pokemon.new(
        img:poke['sprites']['other']['dream_world']["front_default"],
        name: poke['forms'][0]['name'], weight: poke['weight'], 
        poke_type: poke['types'][0]['type']['name'], 
        poke_ability: poke['abilities'][0]['ability']['name'], 
        poke_id: poke['id']
      )
    end
  end
end

然后只需在您的控制器中调用该方法

def index
  render json: { pokemons: PokemonApi.to_json }
end