Module: Dynomite::DbConfig::ClassMethods

Defined in:
lib/dynomite/db_config.rb

Constant Summary collapse

@@db =
nil

Instance Method Summary collapse

Instance Method Details

#check_dynamodb_local!(endpoint) ⇒ Object

When endoint has been configured to point at dynamodb local: localhost:8000 check if port 8000 is listening and timeout quickly. Or else it takes a for DynamoDB local to time out, about 10 seconds… This wastes less of the users time.



37
38
39
40
41
42
43
44
# File 'lib/dynomite/db_config.rb', line 37

def check_dynamodb_local!(endpoint)
  return unless endpoint && endpoint.include?("8000")

  open = port_open?("127.0.0.1", 8000, 0.2)
  unless open
    raise "You have configured your app to use DynamoDB local, but it is not running.  Please start DynamoDB local. Example: brew cask install dynamodb-local && dynamodb-local"
  end
end

#dbObject



22
23
24
25
26
27
28
29
30
31
# File 'lib/dynomite/db_config.rb', line 22

def db
  return @@db if @@db

  config = db_config
  endpoint = ENV['DYNAMODB_ENDPOINT'] || config['endpoint']
  check_dynamodb_local!(endpoint)

  Aws.config.update(endpoint: endpoint) if endpoint
  @@db ||= Aws::DynamoDB::Client.new
end

#db=(db) ⇒ Object

useful for specs



62
63
64
# File 'lib/dynomite/db_config.rb', line 62

def db=(db)
  @@db = db
end

#db_configObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/dynomite/db_config.rb', line 66

def db_config
  return @db_config if @db_config

  if defined?(Jets)
    config_path = "#{Jets.root}config/dynamodb.yml"
    env = Jets.env
  else
    config_path = ENV['DYNOMITE_CONFIG'] || "./config/dynamodb.yml"
    env = ENV['DYNOMITE_ENV'] || "development"
  end

  config = YAML.load(Dynomite::Erb.result(config_path))
  @db_config ||= config[env] || {}
end

#get_table_namespaceObject



90
91
92
93
94
95
# File 'lib/dynomite/db_config.rb', line 90

def get_table_namespace
  return @table_namespace if defined?(@table_namespace)

  config = db_config
  @table_namespace = config['table_namespace']
end

#port_open?(ip, port, seconds = 1) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/dynomite/db_config.rb', line 47

def port_open?(ip, port, seconds=1)
  # => checks if a port is open or not
  Timeout::timeout(seconds) do
    begin
      TCPSocket.new(ip, port).close
      true
    rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, SocketError
      false
    end
  end
rescue Timeout::Error
  false
end

#set_table_namespace(value) ⇒ Object



97
98
99
# File 'lib/dynomite/db_config.rb', line 97

def set_table_namespace(value)
  @table_namespace = value
end

#table_namespace(*args) ⇒ Object



81
82
83
84
85
86
87
88
# File 'lib/dynomite/db_config.rb', line 81

def table_namespace(*args)
  case args.size
  when 0
    get_table_namespace
  when 1
    set_table_namespace(args[0])
  end
end