i am trying to retrieve a row from a dataset
my model class is
require 'sequel'
class Item < Sequel::Model
end
and one my hello.rb file is
require "rubygems"
require './post'
require "sequel"
require './item'
# connect to an in-memory database
#DB = Sequel.connect('postgres://ritesh:newpassword#localhost')
puts Item.filter(:id =>'1').first
its giving me output
#<Item:0xb693996c>
i want to get all the columns of the row whose id field is 1 what should be the query??
try
puts Item.filter(:id =>'1').first.inspect
or
puts Item.filter(:id =>'1').first.to_yaml
(for better formatting if you have yaml required in your code like so require 'yaml')
Related
I am creating a scraper with Nokogiri and Ruby on Rails. My goal is to scrape jobs from a specific webpage. I created the following code, which results in an array of job titles. So this works fine.
My problem is now, that I want to add these titles to my database of Vacancies. When I type in Vacancy.create(companyname=jobs[0]), it should create a Vacancy with the first job-title in the array.
But it gives me an error instead:
app/services/job_service.rb:18:in `': uninitialized constant
Vacancy (NameError)
So it looks like it does not know the class Vacancy.
I therefore required the file vacancy.rb:
require_relative(../models/vacancy.rb')
But then it gives me another error:
uninitialized constant ApplicationRecord (NameError)
So I now think that I am doing something fundamentally wrong here.
Am I putting the whole scraper file in the wrong folder (should I probably put it in the rake folder)?. All I want is to execute something like Vacancy.create so that it pushes this to my database of Vacancies (aka Jobs).
Here is the the scraper (job_service.rb):
require 'open-uri'
require 'nokogiri'
url = "https://www.savedroid.com/#karriere-section"
html_file = open(url).read
html_doc = Nokogiri::HTML(html_file)
jobs = []
html_doc.search('.job').each do |element|
jobs << element.text.strip
end
Vacancy.create(companyname=jobs[0])
make sure that the model is created and there are necessary fields in the table
let's put you code of parser into the rails services:
class Jobs
def self.jobs
return #jobs if #jobs
require 'open-uri'
require 'nokogiri'
url = "https://www.savedroid.com/#karriere-section"
html_file = open(url).read
html_doc = Nokogiri::HTML(html_file)
jobs = []
html_doc.search('.job').each do |element|
jobs << element.text.strip
end
#jobs = jobs
end
end
then you can call it inside rails controller:
VacancyController < ApplicationController
def create
Jobs.jobs.each do |job|
Vacancy.create(companyname: job)
end
end
end
I am trying to seed my database with some dummy data, so I have this seed file:
db/seeds.rb
require 'require_all'
require_all 'lib'
Author.create(name: "Mark Twain")
My Ruby model and relevant methods:
lib/author.rb
class Author
attr_accessor :name, :id
def initialize(name, id=nil)
#name = name
#id = id
end
def self.make_object_from_row(row)
# [1, "Mark Twain"]
Author.new(row[1], row[0])
end
def self.create(name)
author = Author.new(name)
author.save
end
def save
if self.id.nil? # doesn't exist in the database yet
sql = <<-SQL
INSERT INTO authors (name)
VALUES (?)
SQL
DB.execute(sql, self.name)
sql = "SELECT last_insert_rowid()"
self.id = DB.execute(sql)[0][0]
else # just update the row in the db
sql = <<-SQL
UPDATE authors SET (name) = ? WHERE id = ?
SQL
DB.execute(sql, self.name, self.id)
end
end
Rakefile
require_relative './config/environment'
desc "Set up database"
task :db_setup do
author_sql = <<-SQL
CREATE TABLE IF NOT EXISTS authors(
id integer PRIMARY KEY,
name varchar(255)
);
SQL
DB.execute(author_sql)
end
desc "Seed database"
task :db_seed do
ruby "db/seeds.rb"
end
config/environment.rb
require 'bundler/setup'
Bundler.require
# setting up the database connection (old way)
DB = SQLite3::Database.new("db/development.db")
require_relative '../lib/author.rb'
When I run the rake task for db_seed I get the error . lib/author.rb:26:in save': uninitialized constant Author::DB (NameError)
The db_setup Rake task works fine. Also if I go into a pry from my console, I can instantiate a new Author without a problem (and it writes to the database). If I run the seed file from my command line, I get the same error.
I see that it's looking for an attribute DB on the Author class, but I don't see why, or why it's inconsistent in that I can create an Author from the command line but not from the Rake task--if the variable were undefined that shouldn't make a difference, correct?
(I'm also aware that using ActiveRecord would be much easier, but I'm not looking to use it right now)
When you see errors like "uninitialized constant" popping up and you're sure you've defined that constant in a file somewhere, make sure you're loading that code in before the method with the error runs.
It looks like in this case config/environment wasn't loaded before DB was referenced, so it can't complete.
Due to how Ruby searches for constants it's presented as Author::DB because the code was running inside of the Author namespace and that's where searches start.
I have an SQLite3 database called sk.db with a table called Sked that displays a schedule of sports matches with a column date. I am simply trying to display today's matches. It appears as though the connection to the database is not working, though I do not get any errors.
I have tried looking through the Sequel documentation to no avail. How can I display results from an existing database in Sinatra?
.rb
require 'date'
require 'sequel'
require 'sinatra'
DB = Sequel.connect("sqlite://sk.db")
class Sked < Sequel::Model
end
schedule = DB.from(:sked)
get '/' do
todaymatches = schedule.where(:date => Date.today)
erb :games
end
.erb
<h1>Games</h1>
<p><%= #todaymatches %></p>
.where doesn't actually retrieve data, but instead returns a dataset. Add an .all to actually retrieve the data
todaymatches = schedule.where(:date => Date.today).all
So, I'm trying to build a quick console program for my development needs, akin to rails console (I'm using Sinatra + DataMapper + pry).
I run it and launch cat = Category.new(name: 'TestCat', type: :referential). It gives me the following error:
Error: Cannot open "/home/art-solopov/Projects/by-language/Ruby/billy-bones/=" for reading.
What could be the cause of the problem?
console:
#!/usr/bin/env ruby
$LOAD_PATH << 'lib'
require 'pry'
require 'config'
binding.pry
lib/config.rb:
# Configuration files and app-wide requires go here
require 'sinatra'
require 'data_mapper'
require 'model/bill'
require 'model/category'
configure :production do
DataMapper::Logger.new('db-log', :debug)
DataMapper.setup(:default,
'postgres://billy-bones:billy#localhost/billy-bones')
DataMapper.finalize
end
configure :development do
DataMapper::Logger.new($stderr, :debug)
DataMapper.setup(:default,
'postgres://billy-bones:billy#localhost/billy-bones-dev')
DataMapper.finalize
DataMapper.auto_upgrade!
end
configure :test do
require 'dm_migrations'
DataMapper::Logger.new($stderr, :debug)
DataMapper.setup(:default,
'postgres://billy-bones:billy#localhost/billy-bones-test')
DataMapper.finalize
DataMapper.auto_migrate!
end
lib/model/category.rb:
require 'data_mapper'
class Category
include DataMapper::Resource
property :id, Serial
property :name, String
property :type, Enum[:referential, :predefined, :computable]
has n, :bills
# has n, :tariffs TODO uncomment when tariff ready
def create_bill(params)
# A bill factory for current category type
case type
when :referential
ReferentialBill.new params
when :predefined
PredefinedBill.new params
when :computable
ComputableBill.new params
end
end
end
If I substitute pry with irb in the console script, it goes fine.
Thank you very much!
P. S.
Okay, yesterday I tried this script again, and it worked perfectly. I didn't change anything. I'm not sure whether I should remove the question now or not.
P. P. S.
Or actually not... Today I've encountered it again. Still completely oblivious to what could cause it.
** SOLVED **
DAMN YOU PRY!
Okay, so here's the difference.
When I tested it the second time, I actually entered a = Category.new(name: 'TestCat', type: :referential) and it worked. Looks like pry just thinks cat is a Unix command, not a valid variable name.
Not answer to the pry question I just generally hate case statements in ruby.
Why not change:
def create_bill(params)
# A bill factory for current category type
case type
when :referential
ReferentialBill.new params
when :predefined
PredefinedBill.new params
when :computable
ComputableBill.new params
end
end
to:
def create_bill(params)
# A bill factory for current category type
self.send("new_#{type}_bill",params)
end
def new_referential_bill(params)
ReferentialBill.new params
end
def new_predefined_bill(params)
PredefinedBill.new params
end
def new_computable_bill(params)
ComputableBill.new params
end
You could make this more dynamic but I think that would take away from readability in this case but if you'd like in rails this should do the trick
def create_bill(params)
if [:referential, :predefined, :computable].include?(type)
"#{type}_bill".classify.constantize.new(params)
else
#Some Kind of Handling for non Defined Bill Types
end
end
Or this will work inside or outside rails
def create_bill(params)
if [:referential, :predefined, :computable].include?(type)
Object.const_get("#{type.to_s.capitalize}Bill").new(params)
else
#Some Kind of Handling for non Defined Bill Types
end
end
No idea why this is not working. It's the first time I am working with Mongo, but from all the docs I have read, this should work? Anyone have any idea what I am missing?
require 'rubygems'
require 'sinatra/base'
require 'mongo_mapper'
mongo_server = '127.0.0.1'
mongo_database = 'inone'
MongoMapper.connection = Mongo::Connection.new(mongo_server)
MongoMapper.database = mongo_database
# DB model
class URLstore
include MongoMapper::Document
key :url_key, String
key :url, String
end
class URLnip < Sinatra::Base
get '/testmongo' do
nipurl = URLstore.new(:url_key => "abc", :url => "www.google.com")
nipurl.save
end
end
Opening the Mongo terminal I can see the DB get's created
> show dbs
inone 0.203125GB
but doing this brings back no results at all
> db.inone.find()
>
or
> db.inone.find({url : 'www.google.com'})
>
same thing nothing.
Shouldn't that be db.urlstore.find()? Or however MongoMapper changes the case. What does show collections in a Mongo shell say after you select the right database?