【问题标题】:Set options conditionally with block使用块有条件地设置选项
【发布时间】:2015-11-27 03:53:14
【问题描述】:

我正在构建一个模块,该模块提供一些使用 Fog gem 与 A​​WS CloudWatch 服务交互的功能。如果您不指定凭证,它将自动使用 ENV 中设置的任何内容或使用运行代码的实例的 IAM 角色。其他时候,我想明确传递凭证以访问其他 AWS 账户。这是一个示例类,演示了我希望它如何工作:

class MyAlarmGetter
  include CloudWatchClient

  default_account_alarms = get_all_alarms

  other_account_alarms = with_aws_credentials(account2) do
    get_all_alarms
  end

  def account2
    {
      aws_access_key_id: 'abc123',
      aws_secret_access_key: 'abc123'
    }
  end
end

这是模块到目前为止的样子:

module CloudWatchClient
  def with_aws_credentials(creds)
    # Set credentials here!
    yield
  end

  def get_all_alarms
    cloud_watch_client.alarms.all
  end

  def cloud_watch_client(creds = ENV['FOG_CREDENTIAL'] ? {} : { use_iam_profile: true })
    Fog::AWS::CloudWatch.new(creds)
  end
end

我一直在想办法只在 with_aws_credentials 块的上下文中覆盖默认凭据。

【问题讨论】:

  • MyAlarmGetter 类中存在语法错误。您忘记了 account2 方法定义的结尾。
  • 修正语法错误,谢谢!

标签: ruby fog


【解决方案1】:

要支持这种接口,您可以将creds 参数保存到实例变量中,例如@creds

module CloudWatchClient
  def with_aws_credentials(creds)
    # set given context
    @creds = creds

    result = yield

    # reset context
    @creds = nil

    result 
  end

  def get_all_alarms
    cloud_watch_client.alarms.all
  end

  def cloud_watch_client(creds = ENV['FOG_CREDENTIAL'] ? {} : { use_iam_profile: true })
    # check if context is given and use it
    creds = @creds || creds

    Fog::AWS::CloudWatch.new(creds)
  end
end

上面的代码只是一个示例,对您的代码进行了最小的修改。

【讨论】:

  • 你能解释一下重置吗?据我了解,仅调用实例变量会导致它成为该方法的返回值,但不会改变它的值。我错过了什么?
  • @Adam 好问题。我错过了 nil 分配,但现在修复了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 2019-12-11
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 2018-12-12
  • 1970-01-01
相关资源
最近更新 更多