I'm sure that I am missing something. Basicaly I want to monitor a logs IO and if a FATAL ERROR is logged to send an email with the error enclosed.
#!/usr/bin/ruby -w
require 'rubygems'
def mailer(line)
date = `date +%D-%T`
f = File.open("/root/error.mail", "w")
f.puts("Subject: Fatal Error on SERVER #{date}\n\n#{line}")
f.close
system("sendmail guy#foo.com.com < /root/error.mail")
end
def fatal_check(file, pattern)
f = File.open(file, "r")
f.seek(0,IO::SEEK_END)
while true do
select([f])
line = f.gets
mailer("#{line}") if line=~pattern
#system("./mailer.rb #{line}") if line=~pattern
end
end
fatal_check("/root/test.log", /FATAL ERROR/)
How about this. You'll need a couple of gems:
gem install file-tail
gem install pony
And then your script:
require 'rubygems'
require 'pony'
require 'file/tail'
def fatal_check(file, pattern)
File::Tail::Logfile.open(file, :backward => 0) do |log|
log.tail do |line|
date = `date +%D-%T`
Pony.mail(:to => 'you#example.com', :from => 'me#example.com', :subject => "There was a nasty error on #{date}", :body => line)
end
end
end
fatal_check(File.dirname(__FILE__) + "/test.log", /FATAL/)
Related
This question already has answers here:
An irritating Issue about ruby hashes
(3 answers)
Closed 7 years ago.
I am creating a CRUD API using Ruby, Sinatra, and MongoDB. I keep getting the following error message and I can't figure out what I've done wrong:
SyntaxError: /yasi.rb:6: syntax error, unexpected =>, expecting '}' Yasi.connect {:server => "localhost", :db => "yasi"} ^ /yasi.rb:6: syntax error, unexpected ',', expecting '}' Yasi.connect {:server => "localhost", :db => "yasi"} ^
Here is what my code looks like:
require 'rubygems'
require 'sinatra'
require 'lib/yasi'
before do
Yasi.connect {:server => "localhost", :db => "yasi"}
end
get "/" do
#yasis = Yasi.find :all
erb :index
end
get "/new" do
erb :new
end
get "/delete/:id" do
Yasi.delete(params[:id])
redirect "/"
end
post "/" do
params.reject! {|k,v| k == "submit"}
Yasi.save(params)
redirect "/"
end
Here is the lib/yasi file:
require 'rubygems'
require 'mongo'
require 'sinatra'
module Yasi
class << self
def connect(config)
#db = Mongo::Connection.new(config[:server],config[:port] || 27017).db(config[:db])
end
def find(search)
if search == :all
#return all
yasi = #db.collection("yasis").find.to_a
return nil_or_array(yasi)
else
return find_with_criteria(search)
end
end
def save(yasi)
stringify_keys(yasi)
#handle author first
if yasi["author"]
stringify_keys(yasi["author"])
author = #db.collection("authors").find_one(yasi["author"])
unless author
author = #db.collection("authors").save(yasi["author"])
end
yasi["author"] = author
end
#db.collection("yasis").save(yasi)
end
def delete(id)
victim = #db.collection("yasis").find_one(Mongo::ObjectID.from_stringid))
#db.collection("yasis").remove(victim) if victim
end
private
def find_with_criteria(search)
stringify_keys(search)
if search["author"]
author = #db.collection("authors").find_one stringify_keys(search["author"])
if author
search[:author] = author
yasi = #db.collection("yasis").find(search).to_a
return nil_or_array yasi
else
nil
end
else
yasi = #db.collection("yasis").find(search).to_a
return nil_or_array(yasi)
end
end
def stringify_keys(hash)
hash.each_key do |key|
hash[key.to_s] = hash.delete(key)
end
hash
end
def nil_or_array(result)
if result.size == 0
return nil
else
return result
end
end
end
end
Couple things. Make sure you're accessing yasi in the correct path. Also, pass a variable referencing your hash as config to Yasi.connect like below:
require './lib/yasi'
before do
config = { :server => "localhost", :db => "yasi" }
Yasi.connect config
end
That should handle the error you've posted about, but I would also double check your indentation in the yasi file to make it easier to troubleshoot.
When i am running shoes.rb file, which contains code to install gem, it throws error.
Undefined method setup for Shoes:Class
Code:
Shoes.setup do
gem 'activerecord' # install AR if not found
require 'active_record'
require 'fileutils'
ActiveRecord::Base.establish_connection(
:adapter => 'postgresql',
:dbfile => 'shoes_app'
)
# create the db if not found
unless File.exist?("shoes_app.sqlite3")
ActiveRecord::Schema.define do
create_table :notes do |t|
t.column :message, :string
end
end
end
end
class ShoesApp < Shoes
require 'note'
url '/', :index
def index
para 'Say something...'
flow do
#note = edit_line
button 'OK' do
Note.new(:message => #note.text).save
#note.text = ''
#result.replace get_notes
end
end
#result = para get_notes
end
def get_notes
messages = []
notes = Note.find(:all, :select => 'message')
notes.each do |foo|
messages << foo.message
end
out = messages.join("n")
end
end
Shoes.app :title => 'Notes', :width => 260, :height => 350
The problem was using Shoes4, where the setup method was unimplemented.
Shoes4 now implements Shoes.setup for backwards compatibility reasons but you don't really need it, so it doesn't do anything except for printing a warning that you should rather do gem install gem_name instead of using Shoes.setup.
This is the Sinatra code that I wrote. All gems exist, the ruby files compiles perfectly but when i go to localhost:4567/ the sinatra app doesnt run. It takes me to the 'Sinatra doesnt know this ditty' page. What mistake am i making here? Is it a syntax issue? I've posted the main ruby file's code here others are just haml files thats all.
require 'bundler'
Bundler.setup(:default)
require 'sinatra'
require 'haml'
require 'twitter'
require 'oauth'
class MyTweetWeek < Sinatra::Base
set :haml, :format => :html5, :attr_wrapper => '"'
enable :sessions, :static, :raise_errors
set :public_dir, File.join(File.dirname(__FILE__), 'public')
get '/' do
haml :index
end
get '/login' do
request_token = consumer.get_request_token(:oauth_callback => ENV['OAUTH_CALLBACK'])
session[:request_token] = request_token.token
session[:request_token_secret] = request_token.secret
redirect request_token.authorize_url
end
get '/oauth_callback' do
request_token = OAuth::RequestToken.new(
consumer,
session[:request_token],
session[:request_token_secret]
)
session[:request_token] = session[:request_token_secret] = nil
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])
session[:access_token] = access_token.token
session[:access_secret] = access_token.secret
redirect '/resume'
end
get '/resume' do
redirect '/' unless authenticated?
today = Date.today #get today's date
monday = today - today.cwday + 1 #calculate Monday
search = Twitter::Search.new
#screen_name = client.verify_credentials.screen_name
#number_of_tweets = 0
#number_of_mentions = 0
results = search.from(#screen_name)
.since_date(monday)
.no_retweets
.per_page(100)
.fetch
#number_of_tweets += results.size
while search.next_page?
results = search.fetch_next_page
#number_of_tweets += results.size
end
search.clear
results = search.q("##{#screen_name.gsub('#', '')}")
.since_date(monday)
.no_retweets
.per_page(100)
.fetch
#number_of_mentions += results.size
while search.next_page?
results = search.fetch_next_page
#number_of_mentions += results.size
end
haml :resume
end
error Twitter::Error::Unauthorized do
redirect '/'
end
not_found do
haml :not_found
end
private
def consumer
#consumer ||= OAuth::Consumer.new(
ENV['CONSUMER_KEY'],
ENV['CONSUMER_SECRET'],
:site => "https://api.twitter.com"
)
end
def client
Twitter.configure do |config|
config.consumer_key = ENV['CONSUMER_KEY']
config.consumer_secret = ENV['CONSUMER_SECRET']
config.oauth_token = session[:access_token]
config.oauth_token_secret = session[:access_secret]
end
#client ||= Twitter::Client.new
end
def authenticated?
!session[:access_token].nil? && !session[:access_secret].nil?
end
end
As you have a modular app do you need to require "sinatra/base" rather than "sinatra"? See here
See Serving a Modular App and add the line run! if app_file == $0 at the end of the class. Also see DavB's answer.
I am trying to access the insides of an ODT file. I'll run it through IRB and it will work perfectly fine but when I try and write a script to do it, it fails with this error:
./replace_odf.rb:3:in `require': no such file to load -- rubygems (LoadError)
from ./replace_odf.rb:3
Here is my code when ran through IRB. As you can see towards the end, it can access the file.
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'zip/zip'
=> true
irb(main):003:0> odt = Zip::ZipFile.open('java.odt')
=> java.odt
irb(main):004:0> odt.entries.each do |entry|
irb(main):005:1* puts entry.name
irb(main):006:1> end
mimetype
Configurations2/statusbar/
Configurations2/accelerator/current.xml
Configurations2/floater/
... etc
Here is my script code. When ran, it gives the error posted above.
require 'rubygems'
require 'zip/zip'
require 'rexml/document'
odt = Zip::ZipFile.open('java.odt')
file1 = odt.entries[0]
odt.entries.each do |entry|
puts entry.name if entry.name =~ /\.xml$/
end
puts odt.read("mimetype")
xml = odt.read("content.xml")
doc = REXML::Document.new(xml)
doc.root.each_element do |o|
o.each_element do |i|
puts i
end
end
I have a nanoc site (so, all static pages) that I'd like to test with unicorn.
The idea behind this is to host this site on heroku then.
The structure is then a rack application.
I have added a config.ru file like:
require 'rubygems'
require 'rack'
require 'rack-rewrite'
require 'rack/contrib'
use Rack::Rewrite do
rewrite '/','/output/index.html'
end
use Rack::Static, :urls => ['/'], :root => "output"
(all my static resources are located in the output directory)
When I run unicorn I got the following error message:
NoMethodError at /output/index.html
undefined method `to_i' for #<Rack::Static:0x10165ee18>
I do not really understand what I am missing here :(
Any idea ?
Thanks and regards,
Luc
with this config.ru, it works :)
require 'rubygems'
require 'rack'
require 'rack/contrib'
require 'rack-rewrite'
require 'mime/types'
use Rack::Deflater
use Rack::ETag
module ::Rack
class TryStatic < Static
def initialize(app, options)
super
#try = ([''] + Array(options.delete(:try)) + [''])
end
def call(env)
#next = 0
while #next < #try.size && 404 == (resp = super(try_next(env)))[0]
#next += 1
end
404 == resp[0] ? #app.call : resp
end
private
def try_next(env)
env.merge('PATH_INFO' => env['PATH_INFO'] + #try[#next])
end
end
end
use Rack::TryStatic,
:root => "output", # static files root dir
:urls => %w[/], # match all requests
:try => ['.html', 'index.html', '/index.html'] # try these postfixes sequentially
errorFile='output/404.html'
run lambda { [404, {
"Last-Modified" => File.mtime(errorFile).httpdate,
"Content-Type" => "text/html",
"Content-Length" => File.size(errorFile).to_s
}, File.read(errorFile)] }
Regards,
Luc