NoMethodError: undefined method in routes_with_grape - ruby-on-rails

I am trying to set up a rails grape api with the below structure.
app
api
api
V1
user.rb
app.rb
I am getting this error when i run routes_with_grape
rake aborted!
NoMethodError: undefined method `ast' for "/api/ping(.json)":String
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/actionpack-4.2.1/lib/action_dispatch/journey/path/pattern.rb:14:in `initialize'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:9:in `new'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:9:in `block (3 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:8:in `each'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:8:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:6:in `each'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:6:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-1.9.3-p551/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-1.9.3-p551/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => routes_with_grape
(See full trace by running task with --trace)
here is my code
user.rb
module V1
class User < Grape::API
desc 'Returns pong.'
get :ping do
{ ping: params[:pong] || 'pong' }
end
end
end
app.rb
class API < Grape::API
prefix 'api'
format :json
mount ::V1::User
end
Thanks!

Ditch that gem and use this code (copied from here):
namespace :grape do
desc "Grape API Routes"
task :routes => :environment do
mapped_prefix = '/api' # where mounted API in routes.rb
params_str = ' params:'
desc_limit = 45
route_info = API.routes.map {|r| [r, r.instance_variable_get(:#options)] }
max_desc_size = route_info.map{|_,info| (info[:description] || '')[0..desc_limit].size }.max
max_method_size = route_info.map{|_,info| info[:method].size }.max
max_version_size = route_info.map{|_,info| info[:version].size }.max
max_path_size = route_info.map{|_,info| info[:path].sub(':version', info[:version]).size }.max
max_params_digits = route_info.map{|_,info| info[:params].size.to_s.size }.max
format_str = format(
'%%%ds %%%ds %%%ds %%%ds%%-%ds | %%%ds%%%ds %%s',
max_desc_size + 1,
max_version_size,
max_method_size,
mapped_prefix.size,
max_path_size,
max_params_digits,
params_str.size)
route_info.each do |_,info|
fields = [
info[:description] ? info[:description][0..desc_limit] : '',
info[:version],
info[:method],
mapped_prefix,
info[:path].sub(':version', info[:version]),
info[:params].size.to_s,
params_str,
info[:params].first.inspect,
]
puts format(format_str, *fields)
info[:params].drop(1).each do |param|
puts format(format_str, *([''] * (fields.size-1)) + [param.inspect])
end
end
end
end
paste it into Rakefile and modify:
route_info = API.routes.map
with your API mounting point in my case:
under app/api/web/api.rb I have
module Web
class API < Grape::API
prefix 'api'
mount Web::V1::Root
# mount API::V2::Root (next version)
end
end
So I replaced API.routes by Web::API.routes

Related

uninitialized constant Rake::TestTask

I am trying to run bundle exec rake redmine:plugins NAME=redmine_checklists RAILS_ENV=production and getting this error
NameError: uninitialized constant Rake::TestTask /usr/share/redmine/lib/tasks/redmine.rake:163:in
`block (3 levels) in <top (required)>' /usr/share/redmine/lib/tasks/redmine.rake:161:in `block (2
levels) in <top (required)>' /usr/share/redmine/lib/tasks/redmine.rake:117:in `block in <top
(required)>' /usr/share/redmine/lib/tasks/redmine.rake:18:in `<top (required)>'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/engine.rb:660:in `block in run_tasks_blocks'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/engine.rb:660:in `each'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/engine.rb:660:in `run_tasks_blocks'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/application.rb:518:in `run_tasks_blocks'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/engine.rb:459:in `load_tasks'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/railtie.rb:190:in `public_send'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/railtie.rb:190:in `method_missing'
/usr/share/redmine/Rakefile:6:in `<top (required)>' /var/lib/gems/2.5.0/gems/rake-
13.0.1/exe/rake:27:in `<top (required)>' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/cli/exec.rb:63:in `load' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/cli/exec.rb:63:in `kernel_load' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/cli/exec.rb:28:in `run' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/cli.rb:476:in `exec' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/vendor/thor/lib/thor/invocation.rb:127:in `invoke_command'
/var/lib/gems/2.5.0/gems/bundler-2.1.4/lib/bundler/vendor/thor/lib/thor.rb:399:in `dispatch'
/var/lib/gems/2.5.0/gems/bundler-2.1.4/lib/bundler/cli.rb:30:in `dispatch'
/var/lib/gems/2.5.0/gems/bundler-2.1.4/lib/bundler/vendor/thor/lib/thor/base.rb:476:in `start'
/var/lib/gems/2.5.0/gems/bundler-2.1.4/lib/bundler/cli.rb:24:in `start'
/var/lib/gems/2.5.0/gems/bundler-
2.1.4/exe/bundle:46:in `block in <top (required)>' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/friendly_errors.rb:123:in `with_friendly_errors' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/exe/bundle:34:in `<top (required)>' /usr/local/bin/bundle:23:in `load'
/usr/local/bin/bundle:23:in
`<main>' (See full trace by running task with --trace)
My /usr/share/redmine/lib/tasks/redmine.rake
namespace :redmine do
namespace :attachments do
desc 'Removes uploaded files left unattached after one day.'
task :prune => :environment do
Attachment.prune
end
desc 'Moves attachments stored at the root of the file directory (ie. created before Redmine 2.3) to their subdirectories'
task :move_to_subdirectories => :environment do
Attachment.move_from_root_to_target_directory
end
desc 'Updates attachment digests to SHA256'
task :update_digests => :environment do
Attachment.update_digests_to_sha256
end
end
namespace :tokens do
desc 'Removes expired tokens.'
task :prune => :environment do
Token.destroy_expired
end
end
namespace :watchers do
desc 'Removes watchers from what they can no longer view.'
task :prune => :environment do
Watcher.prune
end
end
desc 'Fetch changesets from the repositories'
task :fetch_changesets => :environment do
Repository.fetch_changesets
end
desc 'Migrates and copies plugins assets.'
task :plugins do
Rake::Task["redmine:plugins:migrate"].invoke
Rake::Task["redmine:plugins:assets"].invoke
end
desc <<-DESC
FOR EXPERIMENTAL USE ONLY, Moves Redmine data from production database to the development database.
This task should only be used when you need to move data from one DBMS to a different one (eg. MySQL to PostgreSQL).
WARNING: All data in the development database is deleted.
DESC
task :migrate_dbms => :environment do
ActiveRecord::Base.establish_connection :development
target_tables = ActiveRecord::Base.connection.tables
ActiveRecord::Base.remove_connection
ActiveRecord::Base.establish_connection :production
tables = ActiveRecord::Base.connection.tables.sort - %w(schema_migrations plugin_schema_info)
if (tables - target_tables).any?
list = (tables - target_tables).map {|table| "* #{table}"}.join("\n")
abort "The following table(s) are missing from the target database:\n#{list}"
end
tables.each do |table_name|
Source = Class.new(ActiveRecord::Base)
Target = Class.new(ActiveRecord::Base)
Target.establish_connection(:development)
[Source, Target].each do |klass|
klass.table_name = table_name
klass.reset_column_information
klass.inheritance_column = "foo"
klass.record_timestamps = false
end
Target.primary_key = (Target.column_names.include?("id") ? "id" : nil)
source_count = Source.count
puts "Migrating %6d records from #{table_name}..." % source_count
Target.delete_all
offset = 0
while (objects = Source.offset(offset).limit(5000).order("1,2").to_a) && objects.any?
offset += objects.size
Target.transaction do
objects.each do |object|
new_object = Target.new(object.attributes)
new_object.id = object.id if Target.primary_key
new_object.save(:validate => false)
end
end
end
Target.connection.reset_pk_sequence!(table_name) if Target.primary_key
target_count = Target.count
abort "Some records were not migrated" unless source_count == target_count
Object.send(:remove_const, :Target)
Object.send(:remove_const, :Source)
end
end
namespace :plugins do
desc 'Migrates installed plugins.'
task :migrate => :environment do
name = ENV['NAME']
version = nil
version_string = ENV['VERSION']
if version_string
if version_string =~ /^\d+$/
version = version_string.to_i
if name.nil?
abort "The VERSION argument requires a plugin NAME."
end
else
abort "Invalid VERSION #{version_string} given."
end
end
begin
Redmine::Plugin.migrate(name, version)
rescue Redmine::PluginNotFound
abort "Plugin #{name} was not found."
end
Rake::Task["db:schema:dump"].invoke
end
desc 'Copies plugins assets into the public directory.'
task :assets => :environment do
name = ENV['NAME']
begin
Redmine::Plugin.mirror_assets(name)
rescue Redmine::PluginNotFound
abort "Plugin #{name} was not found."
end
end
desc 'Runs the plugins tests.'
task :test do
Rake::Task["redmine:plugins:test:units"].invoke
Rake::Task["redmine:plugins:test:functionals"].invoke
Rake::Task["redmine:plugins:test:integration"].invoke
end
namespace :test do
desc 'Runs the plugins unit tests.'
Rake::TestTask.new :units => "db:test:prepare" do |t|
t.libs << "test"
t.verbose = true
t.pattern = "plugins/#{ENV['NAME'] || '*'}/test/unit/**/*_test.rb"
end
desc 'Runs the plugins functional tests.'
Rake::TestTask.new :functionals => "db:test:prepare" do |t|
t.libs << "test"
t.verbose = true
t.pattern = "plugins/#{ENV['NAME'] || '*'}/test/functional/**/*_test.rb"
end
desc 'Runs the plugins integration tests.'
Rake::TestTask.new :integration => "db:test:prepare" do |t|
t.libs << "test"
t.verbose = true
t.pattern = "plugins/#{ENV['NAME'] || '*'}/test/integration/**/*_test.rb"
end
desc 'Runs the plugins ui tests.'
Rake::TestTask.new :ui => "db:test:prepare" do |t|
t.libs << "test"
t.verbose = true
t.pattern = "plugins/#{ENV['NAME'] || '*'}/test/ui/**/*_test.rb"
end
end
end
end
# Load plugins' rake tasks
Dir[File.join(Rails.root, "plugins/*/lib/tasks/**/*.rake")].sort.each { |ext| load ext }
Rails -v
6.0.3.2
Ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]
gem list rake
rake (13.0.1, 12.3.1)
I have tried to remove Rake::TestTask from redmine.rake but it caused more errors. I am not good at ruby-on-rails and I am just trying to install a redmine plugin.
You need to require "rake/testtask" add this in rake file in order to use Rake::TestTask
Refer article Creating a test rake task

Rails populate db rake task OpenURI::HTTPError: 500 Internal Server Error

I am trying to make rake task to populate db from JSON API fixer.io,
but when i type my rake :
rake db:populate
this error occurs:
OpenURI::HTTPError: 500 Internal Server Error
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:16:in `block (5 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:13:in `block (4 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `block (3 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:populate
(See full trace by running task with --trace)
This is my rake task (populate.rake) in lib/tasks:
require 'open-uri'
namespace :db do
desc "Erase and fill database"
task :populate => :environment do
require 'populator'
[ConversionRate].each(&:delete_all)
n = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys.count
currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
currencies.each do |curr1|
currencies.each do |curr2|
ConversionRate.populate 1 do |cr|
cr.currency1 = curr1
cr.currency2 = curr2
cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
end
end
end
end
end
Please help me, I have no idea what causes this problem.
the main problem is here, you are not taking keys of "rates"
currencies = JSON.load(open('http://api.fixer.io/latest')).keys
currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
require 'open-uri'
namespace :db do
desc "Erase and fill database"
task :populate => :environment do
require 'populator'
[ConversionRate].each(&:delete_all)
latest_data = JSON.load(open('http://api.fixer.io/latest'))
currencies = latest_data["rates"].keys
n = currencies.count
currencies.each do |curr1|
currencies.each do |curr2|
ConversionRate.populate 1 do |cr|
#take care of any error, as we are going to call third party api here
begin
cr.currency1 = curr1
cr.currency2 = curr2
cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
rescue => e
puts "error #{e}"
end
end
end
#give a bit rest
sleep 2
end
end
end

rake aborted! LoadError: cannot load such file -- httparty

I'm have the following in my seed.rb file:
require 'httparty'
require 'nokogiri'
require 'awesome_print'
BASE_URL = "http://www.legacy.com/funeral-homes/"
URL_PATH = "directory/"
def get_states(key, value)
arry = []
i = 1
while i <= value do
response = HTTParty.get(BASE_URL + URL_PATH + "#{key}" + "?page=#{i}")
page = Nokogiri::HTML(response.body)
rows = (page.css("div.fhlistitem").select {
|e| !e.content.squeeze(" ").strip.empty? }).map {
|e| [e.css('div.fhname a').first['href'],
e.content.squeeze("").strip.split("\r\n").compact ]
}
rows.each do |row|
row[1].delete(" ")
hash = {
"name" => row[1][0].strip,
"address" => row[1][1].strip,
"phone" => row[1][4].nil? ? "" : row[1][4].strip,
"email" => row[1][5].nil? ? "" : row[1][5].strip,
"license" => row[1][6],
"url" => row[0]
}
arry << hash
end
i += 1
end
arry
end
fhs = get_states("alaska", 4)
fhs.each do |fh|
FuneralHome.create(
name: fh["name"],
address: fh["address"],
phone: fh["phone"],
email: fh["email"],
license: fh["license"],
url: fh["url"],
)
end
When I run rake db:seed I get the following error:
WARN: Unresolved specs during Gem::Specification.reset:
mini_portile (~> 0.6.0)
WARN: Clearing out unresolved specs.
Please report a bug if this causes problems.
rake aborted!
Don't know how to build task 'db:seet'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/task_manager.rb:62:in `[]'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/application.rb:149:in `invoke_task'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/application.rb:106:in `block (2 levels) in top_level'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/application.rb:106:in `each'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/application.rb:106:in `block in top_level'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/application.rb:115:in `run_with_threads'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/application.rb:100:in `top_level'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/application.rb:78:in `block in run'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/application.rb:176:in `standard_exception_handling'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/application.rb:75:in `run'
/usr/local/lib/ruby/gems/2.1.0/gems/rake-10.3.2/bin/rake:33:in `<top (required)>'
/usr/local/bin/rake:23:in `load'
/usr/local/bin/rake:23:in `<main>'
I'm not sure how to interpret the error. I'm requiring 'httparty' in the file. How can I run a HTTParty GET request in my seed.rb file? Or is the a better alternative?
Don't know how to build task 'db:seet'
Maybe this is a problem: try to use "rake db:seed" instead of "rake db:seet"

in `escape': undefined method `gsub' for #<URI::HTTP:0x007fa07cb01e08> (NoMethodError)

Hi I am trying to scrape a web page "take the links" go to that links and "to scrape it" too.
require 'rubygems'
require 'scrapi'
require 'uri'
Scraper::Base.parser :html_parser
web = "http://......"
def sub_web(linksubweb)
uri = URI.parse(URI.encode(linksubweb))
end
scraper = Scraper.define do
array :items
process "div.mozaique>div", :items => Scraper.define {
process "p>a", :title => :text
process "div.thumb>a", :link => "#href"
result :title, :link,
}
result :items
end
uri = URI.parse(URI.encode(web))
scraper.scrape(uri).each do |pag|
link_full = uri + pag.link.to_str
puts pag.title
sub_web(link_full)
puts
end
And I have the following error
e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/sss/web/app/views/admin/topics/webconector.rb
Title 1
http://mydomain/user34/top5
/Users/sss/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/uri/common.rb:304:in `escape': undefined method `gsub' for #<URI::HTTP:0x007fa07cb01e08> (NoMethodError)
from /Users/sss/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/uri/common.rb:623:in `escape'
from ../app/views/admin/topics/conectaweb.rb:11:in `sub_web'
from ../app/views/admin/topics/conectaweb.rb:34:in `block in <top (required)>'
from ../views/admin/topics/conectaweb.rb:29:in `each'
from ../app/views/admin/topics/conectaweb.rb:29:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
Process finished with exit code 1
try using uri = URI.parse(URI.encode(linksubweb.to_s)) this should work. The problem is that method requires a string argument so you have to first convert the URI::HTTP object into string.

How to write task for reindex all ES indexes in Tire?

For now I have:
desc "Index Elastic Search"
namespace :tire do
namespace :import do
task all: :environment do
aliases = Tire::Configuration.client.get(Tire::Configuration.url + '/_aliases').body
indexes_names = MultiJson.load(aliases).keys
indexes_names.each do |name|
index = Tire::Index.new name
index.delete
index.import
index.refresh
puts "[INFO] #{name} re-indexed"
end
end
end
end
But I get an error
wrong number of arguments (0 for 1)
/Users/rege/.rvm/gems/ruby-1.9.3-p194#network/gems/tire-0.5.2/lib/tire/index.rb:185:in `import'
/Users/rege/Code/Network/lib/tasks/tire.rake:15:in `block (4 levels) in <top (required)>'
/Users/rege/Code/Network/lib/tasks/tire.rake:12:in `each'
/Users/rege/Code/Network/lib/tasks/tire.rake:12:in `block (3 levels) in <top (required)>'
Tasks: TOP => tire:import:all
You need to tell each index what to import. Assuming you use the default index naming convention, then you need to do this:
index.import name.singularize.camelcase.constantize.all
UPDATE:
Given your naming style, you can use this:
index.import name.gsub(/^myapp_(development|production)__/, '').singularize.camelcase.constantize.all

Resources