How to pass ec2 instances details to sqlite db using ruby? - ruby

I have the following code:
require 'rubygems'
require 'aws-sdk'
require 'sqlite3'
require 'active_record'
db = SQLite3::Database.new('awsec2.db')
ActiveRecord::Base.establish_connection(
:adapter=> "sqlite3",
:database=> "awsec2")
ActiveRecord::Schema.define do
create_table :instances do |t|
t.column :instance_id, :string
t.column :status, :string
end
end
ACCESS_KEY_ID = '.......................'
SECRET_ACCESS_KEY = '....................'
ec2 = AWS::EC2.new(:access_key_id => ACCESS_KEY_ID, :secret_access_key => SECRET_ACCESS_KEY)
ec2.instances.inject({}) { |m, i| m[i.id] = i.status; m } # How to pass those items to the instances table
How to store the data collected by ec2.instances methode to the database table?

Here is metadata query tool made by amazon. It is just a helper script to fetch data from metadata url.

Related

Can't connect to local MySQL server through socket. I want to connect to REMOTE db

This is my code.
I want to connect to remote database
require 'bundler/setup'
#require "mysql"
#require 'mysql2'
#require "active_record"
Bundler.require
#db_host = ENV["HOST"]
#db_user = ENV["USER"]
#db_pass = ENV['PASSWORD']
#db_name = "db_name"
require "active_record"
ActiveRecord::Base.establish_connection(
:adapter => 'mysql2',
:database => #db_name,
:username => #db_user,
:password => #db_pass,
:host => #db_host)
class ConversionRate < ActiveRecord::Base
end
class ConversionRateMonthly < ActiveRecord::Base
self.table_name = "conversion_rates_monthly"
end
class KdpReport < ActiveRecord::Base
end
class SalesCalculator
def run
p KdpReport.count
end
end
calculator = SalesCalculator.new
calculator.run
But I get this error:
/home/jonsdirewolf/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/mysql2-0.4.9/lib/mysql2/client.rb:89:in `connect': Can't connect to local MySQL server through socket
'/var/run/mysqld/mysqld.sock' (2) (Mysql2::Error)
It is strange but yesterday my code worked. what may be wrong? I want to connect to remote db, not local. And btw I use ruby without rails.
So, the problem is in empty environment var ENV["HOST"].
When host, passed to ActiveRecord is nil or equl to string localhost - AR will try to connect to db using socket.

Seed Data onto Database in an ruby program using activerecord

How can I seed some data to an table using active record in an standalone ruby program?
So far my code is:
require 'prawn'
require 'active_record'
require 'pg'
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
database: 'sample',
username: 'postgres',
password: '...'
)
ActiveRecord::Schema.define do
create_table :xmldata, force: true do |t|
t.text :xmlstr
end
end
Make sure you create table only if it does not exist:
ActiveRecord::Schema.define do
if not connection.table_exists? :xmldata
create_table :xmldata, force: true do |t|
t.text :xmlstr
end
end
end
end
Create an ActiveRecord model for the table.
class Xmldata < ActiveRecord::Base
end
Create objects and save them
Xmldata.create({xmlstr: "<person><name>SOuser</name></person>"})

how do I read from a Database in ruby sinatra using active record

I want to read entrys from a Database using active_record and keep getting diffrent Errors like: Name error and can't find the database or it can't execute the query.
so my question here is how do i read from a database or execute SQL-queries and for example write the result into a variable?
require 'rubygems'
require 'sinatra'
require 'active_record'
require 'sqlite3'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "test.db"
)
class Article < ActiveRecord::Base
end
#ActiveRecord::Migration.create_table :users do |t|
# t.string :name
#end
class App < Sinatra::Application
end
get '/' do
output = users.select(:all)
f = File.open('name','a'); f.write(output); f.close
#puts User.first
To read the data from the users table, you'd simply do:
class User < ActiveRecord::Base
end
get '/' do
#users = User.all
puts "Grabbed #{#users.size} user(s) from database"
end

ActiveRecord and sqlite3 : find does not accept any condition?

I have a problem I can't figure out here. I'm writing a ruby script that deals with an sqllite database.
require 'rubygems'
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "../database/my.db"
)
class KeyWord < ActiveRecord::Base
set_table_name "keywords"
end
# THIS STATEMENT WORKS (finds the first record, returns "ruby") :
KeyWord.find(1).keyval
# THOSE STATEMENTS RETURN NO RESULT :
KeyWord.find(:all, :conditions => {:keyval => "ruby"})
KeyWord.find_by_sql("SELECT * FROM keywords WHERE keyval='ruby'")
KeyWord.find_by_keyval("ruby")
This is how the table was created :
create_table :keywords do |table|
table.column :keyval, :text
end
Does anyone know where this could come from ?
Thanks,
R.
I see a couple of issues here.
I'm not sure why you're manually setting your table name.
ActiveRecord assumes that your model name is camelCased. So... AR
would, by default, search for a table called key_words. Why not just
go with that?
Pay attention to which version of active record you are
using. Passing in conditions is deprecated. You should be using the
.where syntax. So... you would need to do KeyWord.where(:keyval
=> 'ruby').first or end in .all for a collection of results.
If you are just fooling around, you can use sqlite3 in memory.
ActiveRecord::Base.establish_connection( adapter: 'sqlite3',
database: ":memory:")
Also don't forget to define your schema!
Here is full code w/ more modern syntax.
require 'rubygems'
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" )
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define(version: 2) do
create_table :key_words do |t|
t.text :keyval
end
end
class KeyWord < ActiveRecord::Base
end
Keyword.create!(:keyval => 'ruby')
# THESE STATEMENTS WORK:
KeyWord.find(1).keyval
KeyWord.where(:keyval => 'ruby').first
KeyWord.where(:keyval => 'ruby').all
KeyWord.find_by_sql("SELECT * FROM key_words WHERE keyval='ruby'")
KeyWord.find_by_keyval("ruby")

Receiving errors when saving Tweets to a database using Sinatra

I'm using Sinatra, EventMachine, DataMapper, SQLite3 and the Twitter Stream API to capture and save tweets. When I run the application from my command line, it seems to continually fail at tweet 50. If I'm not saving the tweets, it can run seemingly forever.
Below is the app code to capture tweets with 'oscar' in them, which provided a very quick stream. Just enter your twitter username and password and run at the command line.
require 'rubygems'
require 'sinatra'
require 'em-http'
require 'json'
require 'dm-core'
require 'dm-migrations'
USERNAME = '<your twitter username>'
PASSWORD = '<your secret password>'
STREAMING_URL = 'http://stream.twitter.com/1/statuses/filter.json'
DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/db/development.db")
class Tweet
include DataMapper::Resource
property :id, Serial
property :tweet_id, String
property :username, String
property :avatar_url, String
property :text, Text
end
DataMapper.auto_upgrade!
get '/' do
#tweets = Tweet.all
erb :index
end
def rip_tweet(line)
#count += 1
tweet = Tweet.new :tweet_id => line['id'],
:username => line['user']['screen_name'],
:avatar_url => line['user']['profile_image_url'],
:text => line['text']
if tweet.save
puts #count
else
puts "F"
end
end
EM.schedule do
#count = 0
http = EM::HttpRequest.new(STREAMING_URL).get({
:head => {
'Authorization' => [ USERNAME, PASSWORD]
},
:query => {
'track' => 'oscars'
}
})
buffer = ""
http.stream do |chunk|
buffer += chunk
while line = buffer.slice!(/.+\r?\n/)
rip_tweet JSON.parse(line)
end
end
end
helpers do
alias_method :h, :escape_html
end
I'm not sure you can safely mix EM and Sinatra in the same process. You might want to try splitting the Sinatra viewer and the EventMachine downloader into separate programs and processes.

Resources