objects/item.rb
# Returns BTC address if possible to get it (one of the existing ones),
# otherwise generate a new one, using the block.
Returns BTC address if possible to get it (one of the existing ones),
otherwise generate a new one, using the block.
Returns BTC address if possible to get it ( one of the existing ones ) otherwise generate a new one using the block .
def btc(lifetime: 30 * 60)
    item = read
    if item['btc'] && item['assigned']
      age = Time.now.to_i - item['assigned']
      return item['btc'] if age < lifetime
      return item['btc'] if item['active'] && item['active'] == 2 && age < lifetime * 10
    end
    found = @aws.query(
      table_name: 'zold-wallets',
      limit: 1,
      index_name: 'queue',
      select: 'ALL_ATTRIBUTES',
      consistent_read: false,
      expression_attribute_values: { ':a' => 1 },
      key_condition_expression: 'active=:a'
    ).items
    if found.empty? || Time.at(found[0]['assigned']) > Time.now - lifetime
      return item['btc'] if item['btc']
      item['btc'] = yield
    else
      expired = found[0]
      prev = item['btc']
      item['btc'] = expired['btc']
      raise "There is no BTC in the table for @#{expired['login']}, while marked as active" if item['btc'].nil?
      if prev.nil?
        expired.delete('btc')
        expired['active'] = 0
      else
        expired['btc'] = prev
      end
      @aws.put_item(table_name: 'zold-wallets', item: expired)
    end
    item['assigned'] = Time.now.to_i
    item['active'] = 1
    @aws.put_item(table_name: 'zold-wallets', item: item)
    item['btc']
  end
def btc ( lifetime : 30 * 60 ) item = read if item [ 'btc' ] && item [ 'assigned' ] age = Time . now . to_i - item [ 'assigned' ] return item [ 'btc' ] if age < lifetime return item [ 'btc' ] if item [ 'active' ] && item [ 'active' ] == 2 && age < lifetime * 10 end found = @aws . query ( table_name : 'zold-wallets' , limit : 1 , index_name : 'queue' , select : 'ALL_ATTRIBUTES' , consistent_read : false , expression_attribute_values : { ':a' => 1 } , key_condition_expression : 'active=:a' ) . items if found . empty? || Time . at ( found [ 0 ] [ 'assigned' ] ) > Time . now - lifetime return item [ 'btc' ] if item [ 'btc' ] item [ 'btc' ] = yield else expired = found [ 0 ] prev = item [ 'btc' ] item [ 'btc' ] = expired [ 'btc' ] raise "There is no BTC in the table for @#{expired['login']}, while marked as active" if item [ 'btc' ] . nil? if prev . nil? expired . delete ( 'btc' ) expired [ 'active' ] = 0 else expired [ 'btc' ] = prev end @aws . put_item ( table_name : 'zold-wallets' , item : expired ) end item [ 'assigned' ] = Time . now . to_i item [ 'active' ] = 1 @aws . put_item ( table_name : 'zold-wallets' , item : item ) item [ 'btc' ] end
Returns BTC address if possible to get it (one of the existing ones),
otherwise generate a new one, using the block.
Returns BTC address if possible to get it ( one of the existing ones ) otherwise generate a new one using the block .
lifetime