post 通过 HTTParty 进行 HTTP 查询

post HTTP query via HTTParty

我想使用 mailerlite API 将订阅者添加到列表

这是 APIdoc 所说的生成请求的内容

$subscriber = array(
    'email' => 'foo@bar.com',
    'name' => 'foo',
    'fields' => array( 
       array( 'name' => 'country', 'value' => "usa" )
    )
);
$subscriber = $ML_Subscribers->setId( LIST_ID )->add( $subscriber );

它会生成这样的查询字符串

email=foo%40bar.com&name=foo&fields%5B0%5D%5Bname%5D=country&fields%5B0%5D%5Bvalue%5D=usa

并将其发送到mailerlite服务器 我的问题是如何通过 ruby HTTParty gem 或 rails 方法

生成字符串

ActiveSupport monkey patches 对象添加#to_query方法,你可以在你的哈希上调用它来获取查询字符串:

subscriber = {
  'email' => 'foo@bar.com',
  'name' => 'foo',
  'fields' => {
    'name' => 'country', 
    'value' => "usa" 
  }
}

subscriber.to_query
"email=foo%40bar.com&fields%5Bname%5D=country&fields%5Bvalue%5D=usa&name=foo"

要生成与 php 代码完全相同的结果,您应该使用此 gem https://rubygems.org/gems/php_http_build_query

使用示例

puts PHP.http_build_query({"a"=>"b","c"=>"d","e"=>[{"hello"=>"world","bah"=>"black"},{"hello"=>"world","bah"=>"black"}]})

#a=b&c=d&e%5B0%5D%5Bbah%5D=black&e%5B0%5D%5Bhello%5D=world&e%5B1%5D%5Bbah%5D=black&e%5B1%5D%5Bhello%5D=world

您可以使用 MailerLite Ruby gem https://github.com/jpalumickas/mailerlite-ruby

client = MailerLite::Client.new(api_key: 'my-secret-api-key')
client.create_subscriber(email: 'john@example.com', name: 'John Smith')