'GMT-05:00) EST' option unexpectedly included in time_zone_select dropdown - ruby-on-rails

(With Rails 3.2.20, ruby 1.9.3)
In my website in production the '(GMT-05:00) EST' option is unexpectedly included in the time_zone_select dropdown:
This timezone does not exists in ActiveSupport::TimeZone::MAPPING. It is injected ActiveSupport::TimeZone.zones_map:
def zones_map
#zones_map ||= begin
new_zones_names = MAPPING.keys - lazy_zones_map.keys
new_zones = Hash[new_zones_names.map { |place| [place, create(place)] }]
lazy_zones_map.merge(new_zones)
end
end
on the line lazy_zones_map.merge(new_zones) because lazy_zones_map contains the "EST" zone.
It does not happen on my development box and does not happen in my Rails production console: ActiveSupport::TimeZone.send :lazy_zones_map returns {"UTC"=>(GMT+00:00) UTC}.
But when I put in my view in production
<%= ActiveSupport::TimeZone.send :lazy_zones_map %>
I get {"UTC"=>(GMT+00:00) UTC, "EST"=>(GMT-05:00) EST}. I don't understand why it happens, any idea?
The #lazy_zones_map definition is
def lazy_zones_map
require_tzinfo
#lazy_zones_map ||= Hash.new do |hash, place|
hash[place] = create(place) if MAPPING.has_key?(place)
end
end
EDIT: the same version of tzinfo is used in production and development, 0.3.44 (I've checked with the command Gem.loaded_specs["tzinfo"]).

Related

getting errors when scrapping data with kimurai ruby on rails

FATAL -- web_scrapper_spider: Spider: stopped: {:spider_name=>"web_scrapper_spider", :status=>:failed, :error=>"#<NameError: uninitialized constant URI::HTTP\n\n raise InvalidUrlError, "Requested url is invalid: #{url}" unless URI.parse(url).kind_of?(URI::HTTP)\n >", :environment=>"development", :start_time=>2022-11-17 19:03:32.418101772 +0530, :stop_time=>2022-11-17 19:03:32.420534612 +0530, :running_time=>"0s", :visits=>{:requests=>0, :responses=>0}, :items=>{:sent=>0, :processed=>0}, :events=>{:requests_errors=>{}, :drop_items_errors=>{}, :custom=>{}}}
~/.rvm/gems/ruby-3.1.2/gems/kimurai-1.4.0/lib/kimurai/base.rb:194:in `request_to': uninitialized constant URI::HTTP (NameError)
raise InvalidUrlError, "Requested url is invalid: #{url}" unless URI.parse(url).kind_of?(URI::HTTP)
^^^^^^
from ~/.rvm/gems/ruby-3.1.2/gems/kimurai-1.4.0/lib/kimurai/base.rb:128:in `block in crawl!'
require 'open-uri'
require 'nokogiri'
require 'kimurai'
class WebScrapper < Kimurai::Base
#name = "web_scrapper_spider"
#engine = :mechanize
#start_urls = ["https://metaruby.com/"]
#config = {
user_agent: "Chrome/68.0.3440.84"
}
def parse(response, url:, data: {})
blogs = []
response.xpath("//table[#class='topic-list']//tbody//tr").each do |tr|
scrapped_data = {
title: tr.at('td[1]//span').text,
category: tr.at('td[1]//div//span').text,
date: tr.at('td[3]').text.strip
}
blogs << scrapped_data
save_to "results.json", scrapped_data.as_json, format: :json
end
end
end
From the logs posted in the question, it is clear that you are using Ruby version 3.1.2.
The gem Kimura that you are using is not maintained since 2020 and hence it is not compatible with Ruby 3.x due to the separation of positional and keyword arguments from 3.0.
Refer to Kimura issue #66 for more details and updates on the reported issue.
For now, you can use the gem Kimura with earlier Ruby versions.
I tried your code with Ruby 2.x and found no issues with the code.

Crash in Rails ActionView related to I18n.fallbacks when invoked from delayed_job

I am trying to send an email from my rails 4 app like so (condensed version from the console):
> ActionMailer::Base.mail(from: 'mail#example.com', to: 'foo#example.com', subject: 'test', body: "Hello, you've got mail!").deliver_later
The mail would be sent by delayed_lob, in my local test setup I trigger it like so:
> Delayed::Job.last.invoke_job
However the job crashes with the following message:
Devise::Mailer#invitation_instructions: processed outbound mail in 56234.1ms
Performed ActionMailer::DeliveryJob from DelayedJob(mailers) in 56880.04ms
TypeError: no implicit conversion of nil into Array
from /Users/de/.rvm/gems/ruby-2.4.0/gems/actionview-4.2.10/lib/action_view/lookup_context.rb:51:in `concat'
from /Users/de/.rvm/gems/ruby-2.4.0/gems/actionview-4.2.10/lib/action_view/lookup_context.rb:51:in `block in <class:LookupContext>'
from /Users/de/.rvm/gems/ruby-2.4.0/gems/actionview-4.2.10/lib/action_view/lookup_context.rb:39:in `initialize_details'
from /Users/de/.rvm/gems/ruby-2.4.0/gems/actionview-4.2.10/lib/action_view/lookup_context.rb:205:in `initialize'
...
I have looked into the code of lookup_context.rb:51 GitHub, the problem is here:
register_detail(:locale) do
locales = [I18n.locale]
locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks # < crashes here
# from the debugger I got:
# I18n.locale => :de
# I18n.fallbacks => {:en=>[]}
So obviously fallbacks does not contain my locale (:de) which results in a nil exception.
Apparently I18n.fallbacks is not configured correctly.
Question: How can I fix this?
I got the answer with the help of this blog post I found: https://sjoker.net/2013/12/30/delayed_job-and-localization/
It contains half of what I need. The proposed solution goes like this:
In order to propagate state from the time of creating a job, that state has to be transferred to the time the job is invoked by storing it on the job object in the database.
In the blog post, the author only stores the current locale to localize the mail at invitation time. However I also needed to store the fallbacks which required a little bit of serialization.
Here is my solution:
# Add a state attributes to delayed_jobs Table
class AddLocaleToDelayedJobs < ActiveRecord::Migration
def change
change_table :delayed_jobs do |t|
t.string :locale # will hold the current locale when the job is invoked
t.string :fallbacks # ...
end
end
end
# store the state when creating the job
Delayed::Worker.lifecycle.before(:enqueue) do |job|
# If Locale is not set
if(job.locale.nil? || job.locale.empty? && I18n.locale.to_s != I18n.default_locale.to_s)
job.locale = I18n.locale
job.fallbacks = I18n.fallbacks.to_json
end
end
# retrieve the state when invoking the job
Delayed::Worker.lifecycle.around(:invoke_job) do |job, &block|
# Store locale of worker
savedLocale = I18n.locale
savedFallbacks = I18n.fallbacks
begin
# Set locale from job or if not set use the default
if(job.locale.nil?)
I18n.locale = I18n.default_locale
else
h = JSON.parse(job.fallbacks, {:symbolize_names => true})
I18n.fallbacks = h.each { |k, v| h[k] = v.map(&:to_sym) } # any idea how parse this more elegantly?
I18n.locale = job.locale
end
# now really perform the job
block.call(job)
ensure
# Clean state from before setting locale
I18n.locale = savedLocale
I18n.fallbacks = savedFallbacks
end
end
You need to configure your default and fallback locale something like below
config.i18n.default_locale = :de
config.i18n.fallbacks = { de: :en }
Please try this. It will fallback to :en if :de is not found

Why don't my locale settings in number_to_currency work?

Per the Rails 3.2 API Docs, to use different locales for number_to_currency, I need to do the following:
<%= number_to_currency(1234567890.506, :locale => :fr) %>
I was expecting the following output:
# => 1 234 567 890,51 €
Even though I literally use that exact thing within my app and it keeps outputting the following:
$1,234,567,890.51
When I check for the available_locales within my app I get the following:
> I18n.available_locales
=> [:en, :de, :es, :fr, :ja, :pl, :"pt-BR", :ru, :sv, :"zh-CN"]
So it SHOULD work, but it doesn't.
What am I missing?
Update 1
Per #s3tjan's comment, I did some digging in that linked Rails issue and that led me to my application.rb where I discovered I18n.enforce_available_locales = false. I changed that to true and restarted the server.
When I tried the above again, I am now getting this error:
ActionView::Template::Error (:fr is not a valid locale):
Not sure how to fix this.
Update 2
So I just realize that I never had a locale file in my config/locales. What I really want is to use the GBP Pounds for currency, so I added an en-GB.yml file in my config/locales, then I restarted my server and console.
In my application.rb, I have the following:
I18n.enforce_available_locales = true
Then I checked my console and got this:
[1] pry(main)> I18n.available_locales
=> [:en, :de, :es, :fr, :ja, :pl, :"pt-BR", :ru, :sv, :"zh-CN", :"en-GB"]
[2] pry(main)>
So the :"en-GB" was added successfully to my app's load path.
But when I do this in my view:
<%= number_to_currency(1234567890.506, :locale => :"en-GB") %>
This is the error I get:
:"en-GB" is not a valid locale excluded from capture due to environment or should_capture callback
ActionView::Template::Error (:"en-GB" is not a valid locale):
So still not working.
Update 3
My en-GB.yml file was taken directly from https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en-GB.yml
So it looks exactly like that. Yet I am still getting the same error:
ActionView::Template::Error (:"en-GB" is not a valid locale):
Synopsis:
Remove custom language ymls and add the correct version of the i18n-rails gem. This resolved this special issue.
Original answer:
Ok my guess is that your en-GB.yml is empty. So it actually finds the file and adds the locale in I18n.available_locales BUT this does not include that all translations are available.
When you look at the format of such a yml file you will recognize they all start with
---
language-code
some_keys: ...
This is what actually is loaded into memory and therefore provides all the available translations. Available locale is just defined by found files in config/locales.
When you check the source of number_to_currency It takes the locale from the options and passes it along the key it looks for to I18n.
I18n.translate(:'number.format', :locale => options[:locale], :default => {})
Since you just say that en-GB is available but don't have the actual keys along the locale in memory you get the missing translation issue.
What I suggest is you either use the content of the linked yml file and paste it into your en-GB.yml or you remove your en-GB.yml and find a 3.2 working i18n-rails version and use it. i18n-rails provides plenty of default translations which are utilized all over default rails.
Addition:
Before you added the en-GB.yml file it actually worked like expected.
When no locale is found it defaults to dollar in here since the currency variable will be just and empty {}.
Somehow, I found the solution that worked for me.
First of all, you need to have a locale file with your requirements in it.
Here is the example of fr.yml file
For an instance, copy and paste this file in app/config/locales/
then restart your console,
then try, number_to_currency(1000.51, locale: :fr)
for sure, you will get '1 000,51 €'
Here is the full list of all supported countries' locale file.
Until and unless you don't have locale file with your format required in it, you won't get the desired result.
my rails version is 3.2.22.5, ruby is 2.4.2(I didnt install below 2.x.x)
I use locale yml from
https://github.com/svenfuchs/rails-i18n/blob/rails-3-x/rails/locale/en-GB.yml
This is work well
<%= number_to_currency(1234567890.506, :locale => :"en-GB") %>
<%= number_to_currency(1234567890.506, :locale => "en-GB") %>
to result
£1,234,567,890.51
and I add fr.yml too like
fr:
...
number:
currency:
format:
...
unit: €
And then this is work too
<%= number_to_currency(1234567890.506, :locale => :fr) %>
to result
€1,234,567,890.51
I didn't change or add configuration. I add only controller, view and locale file. And test it.
You could translate directly like, so test this
I18n.translate(:'number.currency.format', :locale => "en-GB", :default => {})
if it occur a same error, then check out you file's name, extension, path.
and you must restart server

Wice_Grid CSV export not working - Uninitialized constant CSV::Writer

I "inherited" a rails aplication running with ruby 1.8.7 in development.
I have a wice_grid table which I'm trying to export in CSV and in development all goes perfect.
When I push it to production, i get the following error:
uninitialized constant CSV::Writer
The production machine is running Ruby 1.9.1 and from what I read, I suppose the problem comes from there.
I've tried to put:
required 'csv'
In the controller or the model, but nothing happens, development works, production does not.
Here is the controller code:
def index
require 'csv'
#service_requests = initialize_grid(ServiceRequest,
:name => "solicitudes",
:order => "created_at" ,
:order_direction => 'desc',
:include => [:user, :service],
:enable_export_to_csv => true,
:csv_file_name => 'Listado de Solicitudes'
)
export_grid_if_requested('solicitudes' => 'service_requests') do
#Si se pulsa en exportar se exportan todos las celdas de la tabla seleccionada (con filtros aplicados)
end
end
Here is the part of the view, which calls a partial:
<%= render :partial => 'service_requests' %>
Here is the partial, cropped for making the question not too long:
<%= grid(#service_requests, :show_filters => :always) do |service_request|
[...]
service_request.column :column_name => 'Nombre' , :attribute_name => 'name', :model_class => User do |sr|
sr.user.name
end
service_request.column :column_name => 'Apellidos' , :attribute_name => 'lastName' , :model_class => User do |sr|
sr.user.lastName
end
[...]
end %>
I read this thread but didnt help me much: write csv in ruby 1.9 and CSV::Writer
Thank you all in advance!
Somewhere, that you haven't posted, you are referencing CSV::Writer. This works locally because you're using Ruby 1.8.7, but your production server is using Ruby 1.9.1. CSV::Writer was deprecated with Ruby 1.9.
From the the docs:
# * The old CSV's Reader and Writer classes have been dropped.
Step one is to upgrade your local Ruby to the same version as the server. This will give you the same error locally, which should go away once you find and remove that CSV::Writer.
The CSV docs give examples of how to use the current CSV class to accomplish what CSV::Writer used to do. Here's an example:
# == Writing
#
# === To a File
#
# CSV.open("path/to/file.csv", "wb") do |csv|
# csv << ["row", "of", "CSV", "data"]
# csv << ["another", "row"]
# # ...
# end
Upgrading Ruby will probably raise other errors. But Ruby 1.8.7 was retired in 2013 so these are problems you're going to want to fix now rather than later.
Good luck!

ArgumentError on application requests

I've written a basic Rails 3 application that shows a form and an upload form on specific URLs. It was all working fine yesterday, but now I'm running into several problems that require fixing. I'll try to describe each problem as best as I can. The reason i'm combining them, is because I feel they're all related and preventing me from finishing my task.
1. Cannot run the application in development mode
For some unknown reason, I cannot get the application to run in development mode. Currently i've overwritten the production.rb file from the environment with the settings from the development environment to get actuall stacktraces.
I've added the RailsEnv production setting to my VirtualHost setting in apache2, but it seems to make no difference. Nor does settings ENV variable to production.
2. ArgumentError on all calls
Whatever call I seem to make, results in this error message. The logfile tells me the following:
Started GET "/" for 192.168.33.82 at
Thu Apr 07 00:54:48 -0700 2011
ArgumentError (wrong number of
arguments (1 for 0)):
Rendered
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.erb
(1.0ms) Rendered
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
(4.1ms) Rendered
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
within rescues/layout (8.4ms)
This means nothing to me really. I have no clue what's going wrong. I currently have only one controller which looks like this:
class SearchEngineController < ApplicationController
def upload
end
def search
#rows = nil
end
# This function will receive the query string from the search form and perform a search on the
# F.I.S.E index to find any matching results
def query
index = Ferret::Index::Index.new :path => "/public/F.I.S.E", :default_field => 'content'
#rows = Array.New
index.search_each "content|title:#{params[:query]}" do |id,score, title|
#rows << {:id => id, :score => score, :title => title}
end
render :search
end
# This function will receive the file uploaded by the user and process it into the
# F.I.S.E for searching on keywords and synonims
def process
index = Ferret::Index::Index.new :path => "public/F.I.S.E", :default_field => 'content'
file = File.open params[:file], "r"
xml = REXML::Document.new file
filename = params[:file]
title = xml.root.elements['//body/title/text()']
content = xml.root.elements['normalize-space(//body)']
index << { :filename => filename, :title => title, :content => content}
file.close
FileUtils.rm file
end
end
The routing of my application has the following setup: Again this is all pretty basic and probably can be done better.
Roularta::Application.routes.draw do
# define all the url paths we support
match '/upload' => 'search_engine#upload', :via => :get
match '/process' => 'search_engine#process', :via => :post
# redirect the root of the application to the search page
root :to => 'search_engine#search'
# redirect all incoming requests to the query view of the search engine
match '/:controller(/:action(/:id))' => 'search_engine#search'
end
If anyone can spot what's wrong and why this application is failing, please let me know. If needed I can edit this awnser and include additional files that might be required to solve this problem.
EDIT
i've managed to get further by renaming one of the functions on the controller. I renamed search into create and now I'm getting back HAML errors. Perhaps I used a keyword...?
woot, finally found the solutions....
Seems I used keywords to define my actions, and Rails didn't like this. This solved issue 2.
Issue 1 got solved by adding Rails.env= 'development' to the environment.rb file

Resources