here's the code, its actually a simple schedule-able program for me to retrieve yahoo finance data and insert it to the database, which later may use the same model to retrieve it from Rails.
require 'rubygems'
require 'active_record'
require 'yaml'
require File.join(File.dirname(__FILE__),"../app/models/http_getter")
require File.join(File.dirname(__FILE__),"../app/models/stock")
logger = Logger.new(File.join(File.dirname(__FILE__),"../log/stocks.log"))
ActiveRecord::Base.establish_connection(YAML.load_file(
File.join(File.dirname(__FILE__),"../config/database.yml"))["development"]
)
ActiveRecord::Base.logger = logger
fields = %w{ symbol current_price update_date update_time change open range_to range_from volumn}
symbol = ARGV[0]
url = "http://sg.finance.yahoo.com"
resource = "/d/quotes.csv?s=#{symbol}&f=sl1d1t1c1ohgv&e=.csv"
data = HttpGetter.csv_start(url,resource,fields)
stock = Stock.new(data)
stock.updated_at = Time.now
unless stock.save
logger.error("ERROR: Can't save the record!")
logger.error("ERROR_OBJ_DUMP: "+stock.inspect)
logger.error("ERROR_DATA_DUMP: "+data.inspect)
else
logger.info("SUCCESS "+stock.updated_at.to_s+": Record Saved. Symbol:"+stock.symbol)
end
Some strange thing happen here, u may see the line stock.updated_at = Time.now logically it should not be presented here... it should use the ActiveRecord's brefore_save callback to fill the attribute. But callbacks seems to be not working if I use ActiveRecord external Rails... :-(
No comments:
Post a Comment